开发者

MVC 2 problem populating text box after post

I have an action in an MVC2 application with the following:

    public ActionResult Index()
    {
        return View(new TestModel() { MyValue = "ValueBeforePost" });
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(TestModel m)
    {
        m.MyValue = "ValueSetInPost";
        return View(m);
    }

In my View I have

<% using (MvcForm f = Html.BeginForm("Index", "Home")) %>
<% { %>
    <%= Html.TextBoxFor(m => Model.MyValue) %>
    <input type="submit" value="Submit" />
<% } %>

After the post, the value in my textbox isn't populated with the new value which I set in my action (m.MyValue = "ValueSetInPost"), it appears to be populated from what ever value is held in Request.Form (in this c开发者_如何学Case Request.Form["MyValue" which is "ValueBeforePost"].

How can I change the value in the post?


You need to manipulate the ModelState for this to work. There's a related question that has more details.

The textbox helpers will use the AttemptedValue from the modelstate to repopulate the textbox with the values posted to the controller. The net effect is that the data in ModelState will override anything you put into the model that is passed to the view in your post action.


You need to remove the value from the ModelState of you intend to modify it or the Html helpers will use the original POSTed value:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(TestModel m)
{
    ModelState.Remove("MyValue");
    m.MyValue = "ValueSetInPost";
    return View(m);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜