ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor d

2019-02-07 07:21发布

问题:

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>

回答1:

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



回答2:

in your POST method you need to do

ModelState.Clear();

to reflect the changes made after the post