Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Property set in controller not showing up in view

This is a pretty simple example.

controller

[httppost]
public ActionResult MyPage(MyModelClass myModel) {
    myModel.someProperty = "b";
    return view(myModel)
}

The typed view contains a hidden field for someProperty

@Html.HiddenFor(model => model.someProperty)

The Get controller sets someProperty to "a"

Yet after a post the value of someProperty in the view is still "a"

That doesn't seem rigth to me. Any insights? Thx

like image 449
nuander Avatar asked Oct 22 '25 03:10

nuander


1 Answers

ModelState keeps the posted value 'a'. And as it has higher priority in populating model values (than the model itself), view renders 'a'. You could remove value from ModelState and let model value be used

[HttpPost]
public ActionResult MyPage(MyModelClass myModel) {
    myModel.someProperty = "b";

    ModelState.Remove("someProperty");    

    return view(myModel);
}
like image 143
archil Avatar answered Oct 24 '25 22:10

archil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!