开发者

aspnetmvc model is updated but doesn't update control

hejdig.

In Aspnetmvc2 I have a model object that I send to a View. A control in the view isn't updated with the value. Why? What obvious trap have开发者_JAVA技巧 I fallen in?

The View:

<%:Html.TextBox(
    "MyNumber", 
    null == Model ? "1111" : Model.MyNumber ) %>
<%:Model.MyNumber%>

is first fetched trough a Get. The "1111" value in the textbox is manually updated to "2222". We post the form to the controller which appends "2222" to the Model object and sends it to the view again.

The Controller:

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public  ActionResult Index( MyModel myModel)
    {
        myModel.MyNumber += " 2222";
        return View(myModel);
    }

Alltogether we get an output like:

<input id="MyNumber" type="text" value="1111">
1111 2222

As you can see the control doesn't use the Model's attribute but instead falls back to thew viewstate that doesn't exist in Aspnetmvc.

(The same happens with Razor.)


That's normal and it is how HTML helpers work : they look first in the model state and then in the model when binding a value. So if you intend to modify some property in the POST action you need to remove it from the model state first or you will always get the old value:

[HttpPost]
public ActionResult Index(MyModel myModel)
{
    ModelState.Remove("MyNumber");
    myModel.MyNumber += " 2222";
    return View(myModel);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜