Как создать сетку в ASP.NET Core MVC с помощью C #, в которую мы вставляем запись и сохраняем все данные в базе данных? - PullRequest
0 голосов
/ 28 мая 2019

Я хочу создать сетку или таблицу, которая принимает несколько данных, как мы делаем в Asp.Net Webforms.

Будет форма с полями «Имя», «Имя», «Класс» и «Пол», а также текстовое поле с кнопкой «Добавить» в конце формы для добавления данных в таблицу / сетку.

Сетка / таблица будут иметь те же столбцы имен, что и имена полей. Сетка / таблица будет ниже формы, а под таблицей / сеткой будет кнопка Сохранить. Когда я нажимаю кнопку Сохранить, данные в таблице / сетке должны сохраняться в базе данных.

Я хочу попробовать это в Asp.Net Core MVC using C# с MS SQL Server на его бэкэнде.

Я ожидаю, что данные формы должны быть добавлены в table/grid, и тогда я смогу сохранить данные в сетке / таблице в базу данных, нажав кнопку Сохранить.

Ребята, у вас есть предложения по этому поводу?

1 Ответ

0 голосов
/ 29 мая 2019

Вы можете попробовать использовать JQuery, чтобы получить список добавленных данных и отправить их на контроллер.

Вот простая демонстрация:

Модель StudentInfo и StudentViewModel

public class StudentInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FName { get; set; }
    public string Class { get; set; }
    public string Gender { get; set; }
}

public class StudentViewModel
{
    public  List<StudentInfo> StudentInfos { get; set; }
}

Контроллер

 [HttpPost]
    public async Task<IActionResult> InsertStudents([FromBody]StudentViewModel studentVM)
    {
        List<StudentInfo> model = studentVM.StudentInfos;
        _context.AddRange(model);
        int insertedRecords=await _context.SaveChangesAsync();
        return Json(insertedRecords);

    }

Вид

<table id="tblStudents" class="table" cellpadding="0" cellspacing="0">
<thead>
    <tr>
        <th style="width:150px">Name</th>
        <th style="width:150px">FName</th>
        <th style="width:150px">Class</th>
        <th style="width:150px">Gender</th>
        <th></th>
    </tr>
</thead>
<tbody>   
</tbody>
<tfoot>
    <tr>
        <td><input type="text" id="txtName" /></td>
        <td><input type="text" id="txtFName" /></td>
        <td><input type="text" id="txtClass" /></td>
        <td><input type="text" id="txtGender" /></td>
        <td><input type="button" id="btnAdd" value="Add" /></td>
    </tr>
</tfoot>
</table>
<br />
<input type="button" id="btnSave" value="Save All" />

JavaScript

@section Scripts
{
<script type="text/javascript">
$("body").on("click", "#btnAdd", function () {
    //Reference the Name and Country TextBoxes.
    var txtName = $("#txtName");
    var txtFName = $("#txtFName");
    var txtClass = $("#txtClass");
    var txtGender = $("#txtGender");

    //Get the reference of the Table's TBODY element.
    var tBody = $("#tblStudents > TBODY")[0];

    //Add Row.
    var row = tBody.insertRow(-1);

    //Add Name cell.
    var cell = $(row.insertCell(-1));
    cell.html(txtName.val());
    //Add FName cell.
    cell = $(row.insertCell(-1));
    cell.html(txtFName.val());
    //Add Class cell.
    cell = $(row.insertCell(-1));
    cell.html(txtClass.val());
    //Add Gender cell.
    cell = $(row.insertCell(-1));
    cell.html(txtGender.val());

    //Clear the TextBoxes.
    txtName.val("");
    txtFName.val("");
    txtClass.val("");
    txtGender.val("");
});


$("body").on("click", "#btnSave", function () {
    //Loop through the Table rows and build a JSON array.
    var students = new Array();
    $("#tblStudents TBODY TR").each(function () {
        var row = $(this);
        var student = {};
        student.Name = row.find("TD").eq(0).html();
        student.FName = row.find("TD").eq(1).html();
        student.Class = row.find("TD").eq(2).html();
        student.Gender = row.find("TD").eq(3).html();
        students.push(student);
    });

    //Populate invoice data
    var studentVM = {};
    studentVM.StudentInfos = students;

    //Send the JSON array to Controller using AJAX.
    $.ajax({
        type: "POST",
        url: "/StudentInfoes/InsertStudents",
        data: JSON.stringify(studentVM),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r + " record(s) inserted.");
        }
    });
});
</script>
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...