1

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 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.)

1 Answer 1

6

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

If that's the case, then what's the point of saying return View(model) (from an Edit Action) if the helpers are going to ignore it anyway? Second point, many of your answers have saved the day for me, as has this one.
@EricNelson, the point is that the model might be used in the view in something different than an HTML helper. For example display some value: <div>@Model.MyNumber</div>. If you do not pass the model to the view then you will get a pretty nice NRE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.