简体   繁体   中英

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);
    }

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM