ASP MVC-3: Problems updating AJAX form data after posting

I am having the following problem when updating a via AJAX after sending it. For some reason, some hidden fields that are in the returned HTML are not updated, which is strange, because when I run the debugger, they seem to have the correct value.

This is an important 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> 

The partial view then contains hidden fields, such as those that are not 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 a 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 a Partial View "ItemData", and when I check the item model, it has the correct value, but when I see the returned html, it is still set to 0.

+4
source share
2 answers

If you intend to change the model property in your POST action, be sure to first remove it from ModelState, otherwise the HTML helpers will use the original 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); } 
+5
source

I have the same problem, and it seems that the HiddenFor helper is evaluated with the necessary unobtrusive check, even if no one annotates the property in the model using [Required] .

HTML displayed by @Html.HiddenFor(m=>m.Step) :

<input data-val=​"true" data-val-number=​"The field Step must be a number." data-val-required=​"The Step field is required." id=​"Step" name=​"Step" type=​"hidden" value=​"2">​

Therefore, therefore, it works if we remove it from ModelState .

Removing a property from ModelState seems hacked to me. I would rather use

<input type="hidden" id="Step" name="Step" value="@Model.Step" />

instead Html.HiddenFor assistant.

You can also implement your own HiddenFor helper.

0
source

Source: https://habr.com/ru/post/1437544/


All Articles