Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following problem when updating a for via AJAX after it is submitted. For some reason some hidden fields that are on the HTML that is returned are not being updated, which is weird because when I run the debugger they appeared to have the correct value.

This is the relevant part of my form

<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>

Then the partial view contains hidden fields like these which are the ones not being updated

@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" }) 

And this is the javascript method that updates the form

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(); }
        });
    }

The action Index returns the Partial View "ItemData" and when I check the Item Model it does have the correct value, but when I see the html returned it is still set to 0.

like image 644
paddingtonMike Avatar asked Oct 03 '12 09:10

paddingtonMike


1 Answers

If you intend to modify a model property in your POST action don't forget to remove it from ModelState first, otherwise HTML helpers will use the originally posted value when rendering:

[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);
}
like image 83
Darin Dimitrov Avatar answered Nov 08 '22 18:11

Darin Dimitrov