Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 541
vborutenko Avatar asked May 07 '13 12:05

vborutenko


1 Answers

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();
like image 71
mattytommo Avatar answered Oct 31 '22 10:10

mattytommo