vborutenko
vborutenko

Reputation: 4443

Change model property in post request asp.net mvc

I have one problem.

This is short example. This is model.

    public class MyModel
    {
         string Title{get;set;}
    }

In view I write

@Html.TextBoxFor(model => model.Title)

This is controller.

    public ActionResult EditNews(int id)
    {
        var model = new MyModel;
        MyModel.Title = "SomeTitle"

        return View("News/Edit", model);
    }
    //for post
    [HttpPost]
    public ActionResult EditNews(MyModel model)
    {
        //There is  problem.When I do postback and
        // change Title in this place,Title  doesn't change in view textbox
        //Only when I reload page it change.
        model.Title = "NEWTITLE"

        return View("News/Edit", model);
    }

Upvotes: 19

Views: 11184

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56429

It won't change because by default (many think this is a bug) MVC will ignore the changes you make to the model in a HttpPost when you're returning the same View. Instead, it looks in the ModelState for the value that was originally served to the view.

In order to prevent this, you need to clear the ModelState, which you can do at the top of your HttpPost by doing:

ModelState.Clear();

Upvotes: 35

Related Questions