Ajax – ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server

ajaxasp.net-mvc-3razor

I'm using the Ajax.BeginForm helper in ASP.NET MVC3 to submit a form that replaces itself with new values in the form set on the server. However when I use helpers like Html.TextBoxFor I get the values that was submitted, not the values I inserted into the model on the server.

For example; I set SomeValue to 4 in my action and show it in a textbox. I change the value to 8, hit submit and would expect the value to be changed back to 4 in the textbox, but for some reason it stays 8. But if I output SomeValue without using Html helpers it says 4. Anybody have some clue about what is going on?

My controller:

public ActionResult Index(HomeModel model)
{
    model.SomeValue = 4;
    if (Request.IsAjaxRequest())
        return PartialView(model);
    return View(model);
}
public class HomeModel
{
    public int? SomeValue { get; set; }
}

My View (please not that I have all the needed javascript in my layout page):

<div id="ajaxtest">
@using(Ajax.BeginForm(new AjaxOptions{ InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "ajaxtest", HttpMethod = "Post" })) {
    @Html.TextBoxFor(model => model.SomeValue)
    <input type="submit" value="Update" />
}
</div>

Best Answer

you can use

ModelState.Clear() 

in your controller method to make the html helpers use your changed model. Otherwise they use the values from the form submit

Have a look at: Asp.net MVC ModelState.Clear

Related Topic