ajax - ASP MVC-3 : Problems updating the data of an AJAX form after making a post

标签 ajax asp.net-mvc jquery

提交后通过 AJAX 更新 for 时遇到以下问题。由于某种原因,返回的 HTML 上的一些隐藏字段没有被更新,这很奇怪,因为当我运行调试器时,它们似乎具有正确的值。

这是我的表单的相关部分

<div id="itemPopUpForm">
    @{Html.EnableClientValidation();}
    @Html.ValidationSummary()
    <div id="formDiv">
        @{ Html.RenderPartial("ItemData", Model, new ViewDataDictionary() { { "Machines", ViewBag.Machines }, { "WarehouseList", ViewBag.WarehouseList }, { WebConstants.FORM_ID_KEY, @ViewData[WebConstants.FORM_ID_KEY] } }); }
    </div>
</div>

然后,部分 View 包含像这样的隐藏字段,这些字段没有被更新

@using (Html.BeginForm("Index", "Item", FormMethod.Post, new { id = "frmItem", name = "frmItem" }))
{ 
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.Item.SodID)
    @Html.HiddenFor(model => Model.Item.ItemID) //The itemID needs updating when an item is copied
    @Html.HiddenFor(model => model.Item.Delivery.DeliveryAddressID, new { @id = "delAddressID" }) 

这是更新表单的 javascript 方法

function ajaxSave() {
        if (!itemValid()) return; 
        popup('ajaxSplash');
        $.ajax({
            type: "POST",
            url: '@Url.Action("Index")',
            data: $("#frmItem").serialize(),
            success: function (html) {
                console.log(html);
                $("#formDiv").html(html);
                initItemPage();
                alert("Item was saved successfully");
            },
            error: function () { popup('ajaxSplash'); onFailure(); }
        });
    }

操作索引返回部分 View “ItemData”,当我检查项目模型时,它确实具有正确的值,但当我看到返回的 html 时,它仍然设置为 0。

最佳答案

如果您打算在 POST 操作中修改模型属性,请不要忘记先将其从 ModelState 中删除,否则 HTML 帮助程序将在渲染时使用最初发布的值:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // remove the value from modelstate
    ModelState.Remove("Item.ItemID");

    // update the value
    model.Item.ItemID = 2;   

    return PartialView(model);
}

关于ajax - ASP MVC-3 : Problems updating the data of an AJAX form after making a post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705838/

相关文章:

.net - Orchard CMS 模块仪表板中的重复模块条目

javascript - HTML 表单 : display a text in an input (textarea)

javascript - 当用户点击 div 水平滚动条箭头时触发事件

javascript - 如何在ajax页面上启用后退按钮

javascript - 如何减少我的 magento 网站弹出窗口中的 js 和 css 加载时间

javascript - 使用 ajax 回调将数据源绑定(bind)到 Controller 时,数据未显示在 Kendo Grid 上

asp.net-mvc - MVC 3 从 web.config 中的 AppSettings 获取值

c# - 如何更改 .Net MVC 中 DateTime 模型 Binder 的默认输入格式?

jquery - 使用 jQuery 遍历 $.get() 的结果

jquery - 隐藏/显示 Div (jQuery)