Frank Thomas
Frank Thomas

Reputation: 2514

MVC5 Unused model fields are lost between GET and POST

If I respond to a GET by populating a Model object with initialization data (like the current username), and no editor for that field is used in the view, when my form posts, the field is nulled out. This appears to be true if I use the DisplayFor or LableFor as well.

Example:

       //ChangeAccountInfo
       [Authorize]
       public ActionResult ChangeSecurityQA() {

          ChangeSecurityQAModel qa = new ChangeSecurityQAModel(@User.Identity.Name);
            //this constructor sets UserName and loads several other fields necessary for the process.
          return View(qa);
       }


       //
       //ChangeSecurityQA Post
       [HttpPost]
       [Authorize]
       public ActionResult ChangeSecurityQA(ChangeSecurityQAModel iModel) { 
           \\iModel.UserName is now null... 
       }

The view in question does not use UserName, but the methods I will call in the POST handler will.

For Username thats not a big deal to just get it again, but for info with a more complicated flow, how can I ensure that information entered into the model by the controllers GET will come back to the POST?

Upvotes: 0

Views: 397

Answers (1)

David
David

Reputation: 219037

That data has to exist in the form somewhere. If there's no field for it, add a hidden one:

@Html.HiddenFor(x=> x.SomeField)

The controller can't pass information directly from one action to another. Any information that needs to exist on the de-serialized model in the target action needs to be de-serialized from the HTTP request, which means it has to be in the form post.

Be aware, of course, that users can see and edit this value. Anything that's sensitive shouldn't be sent to the user, and anything that comes from user should be validated.

Upvotes: 3

Related Questions