如何使用AJAX和JQuery保存模型

时间:2013-12-02 10:54:47

标签: javascript jquery ajax asp.net-mvc-4 xhtml

我正在尝试做一个表格,我可以在其中添加新项目,删除和编辑选定的行。

编辑或创建新行后,当我点击“保存”按钮时,我想将模型发送到控制器并更新我的视图。

我正在尝试将模型发送到控制器,但我的代码无效。任何人都可以解释我为什么,我可以解决它吗?

我的JQuery代码:

function saveUpdates(tableId, model) {
showInitialBtns();

transformInputToText();

var modelData = JSON.parse(model);

$.ajax({
    cache: false,
    type: "POST",
    url: "Backoffice/SaveRow",
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify(modelData),
    success: function () {
       updateTable();
    }
});

}

我的观点:

    @model IEnumerable<projetoTeste.Model.BackOffice.Car>


<table class="table" id="container">
    <thead>
        <tr>
            <th rowspan="2">
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th rowspan="2">
                @Html.DisplayNameFor(model => model.Owner)
            </th>
            <th colspan="4">
                Other data
            </th>
        </tr>
        <tr>
            <th colspan="2">
                @Html.DisplayNameFor(model => model.DateRegiste)
            </th>
            <th colspan="2">
                @Html.DisplayNameFor(model => model.DateBuy)
            </th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayFor(model => model)
    </tbody>
</table>


<div id="initialButtons" style="display: block">
    <p>
        <button id="btnAdd" type="button" class="enable">
            Add new row</button>
        <button type="button" class="disable" id="btEdit">
            Edit</button>
        <button type="button" class="disable" id="btDelete">
            Delete</button>
    </p>
</div>

<div id="btnsEditing" style="display: none">
    <p>
        <button id="btSaveEdition" type="button" class="enable" onclick="saveUpdates('container','@(Model)')">
            Save</button>
        <button id="btCancelEdition" type="button" class="enable">
            Cancel</button>
    </p>
</div>

我的控制器:

public void SaveRow(ICollection<AnatomicLocation> item)
{ 
   //some code
}

1 个答案:

答案 0 :(得分:0)

我找到了一些答案:

  1. 我可以将新行追加到表中并提交所有表 之后,像这样:

    $.get(newRowUrl + rowSelectedId, function(data) {
         $("#" + tableId + " tbody").append(data);    
    });
    

    请注意,定义每个名称的正确名称至关重要 表中新行的元素因为我们正在讨论a 收集数据。例如:

    @{
         string modelFieldInitialName = "Car[" + Model.Id + "].";
         string modelFieldInitialId = "Car_" + Model.Id + "_"; 
    } 
    @Html.HiddenFor(model => model.Id, new { Name = modelFieldInitialName + "Id", id = modelFieldInitialId + "Id" })
    
  2. 或者,我们可以搜索行项并按以下方式提交:

    var selectedOption = $("#" + tableId + " tbody tr#" + rowSelectedId).serialize();
    
    $.ajax({
       url: newRowUrl + rowSelectedId,
       type: 'POST',
       async: true,
       data: selectedOption,
       success: function () { },                            
       error:function () { },
    });