jquery remove导致mvc3 post失败

时间:2012-09-26 00:17:10

标签: javascript jquery asp.net-mvc-3 post

我有一个动态生成行的HTML表(使用MVC3的EditorFor)。用户填写表中的数据(逐行),然后将表单提交给服务器(通过MVC3 HTML表单)。用户可以通过按下在TR元素上调用$(tableRow).remove()的按钮来删除行,然后调用从数据库中删除该行的异步服务器方法。

我发现如果我在表中说了5行而我删除了第3行然后提交,则服务器方法接收第1行和第2行,但是丢失其他行(原始的第4行和第5行)。

我已经尝试在线搜索为什么回发会收到前两行而错过最后两行,但我能找到的所有答案都围绕着JQuery帖子,我没有使用。

任何帮助或方向都会很棒,如果我需要澄清任何事情,请告诉我。

编辑:从我的项目中添加适用于该问题的代码。如果您需要更多上下文代码,请告诉我,我会添加它。

//////////////// VIEW ////////////////
// model info and initialization logic
@using (Html.BeginForm("EditTimesheet", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "editTimesheet" }))
{
@Html.ValidationSummary(true)
<fieldset>
<table width="100%">
<tr>
    <td colspan="14" align="right">
    // lots of code
    </td>
</tr>
@Html.EditorFor(m => m.Rows)
<tr>
    <td colspan="14" align="right">
    // lots of code
    </td>
</tr>
// closing statements

//////////////// EditorFor ////////////////
// model info and initialization logic
<tr class="timesheet-row">
    <td>
        <a href='#'>
            <img src='@Url.Content("~/Content/Images/delete.gif")' 
                     width='17' height='17' style='border: 0;' 
                     onclick="DeleteRow(this, @Model.RowId)" />
        </a>
    </td>  
    // other td's
</tr>

//////////////// JS file ////////////////
function DeleteRow(box, rowId)
{
    $(box).closest(".timesheet-row").remove();

    // HACK: despicable, detestable HACK!
    var url = deleteRowUrl;
    url += '?rowId=' + rowId;
    var ajaxData = {
        type: "POST",
        url: url,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: null,
        success: null,
        error: function (error) {
            alert("There was an error posting the data to the server: " + error.responseText);
        }
    };
    $.ajax(ajaxData);
}

2 个答案:

答案 0 :(得分:2)

当你删除一行时,你正在集合中名称的索引中创建 holes ,默认模型绑定器会停止工作,因为你不再尊重预期的格式。

所以不要使用以下顺序值:

<input type="text" name="Items[0].Id" value="1" />
<input type="text" name="Items[1].Id" value="2" />
<input type="text" name="Items[2].Id" value="3" />
<input type="text" name="Items[3].Id" value="4" />
<input type="text" name="Items[4].Id" value="5" />

如果删除TR元素上带有$(tableRow).remove()的第三行,则最终得到:

<input type="text" name="Items[0].Id" value="1" />
<input type="text" name="Items[1].Id" value="2" />
<input type="text" name="Items[3].Id" value="4" />
<input type="text" name="Items[4].Id" value="5" />

看到问题?

这里的an article说明了如何通过使用名为Html.BeginCollectionItem的自定义帮助程序来解决此问题,该帮助程序在集合的输入字段名称中使用GUID而不是整数索引。另请查看Phil Haacks article,了解默认模型绑定器期望命名字段的语法。最后有一个部分叫做 Non-Sequential Indices ,其中介绍了如何做到这一点。

答案 1 :(得分:0)

声音部分正在被删除。

  1. Inspect the DOM
  2. 找到你的表格
  3. 删除行并查看更改内容