Reputation: 2863
I have a simple account updating form that posts to an Update() function. A model with the current user's account info is passed to the view containing this form, so the fields are automatically filled out.
The form
@model SomeController.AccountModel
@using (Html.BeginForm("Update", "SomeController", FormMethod.Post)) {
@Html.LabelFor(u => u.Username)
@Html.TextBoxFor(u => u.Username)
...
There are backups of every property, such as backupUsername
, so that I can search the database for the old one and update from that.
Update()
[HttpPost]
public ActionResult Update(AccountModel newInfo)
{
System.Diagnostics.Debug.WriteLine(newInfo.backupUsername);
return Something();
}
When I submit the form however, a completely new model is passed in, as newInfo.backupUsername
is blank. How do I get the same model to be passed back?
Upvotes: 0
Views: 61
Reputation: 25221
A new model is always created - there's no automatic persistence of view models over multiple requests (without manually using session state or some other mechanism) as HTTP is stateless. The model that appears in your POST action is created by binding fields from your form to that object. If the fields aren't there, nothing will be bound.
You have a few options here. The first is to add hidden fields into your view, so the model binder will pick them up:
@Html.HiddenFor(m => m.backupUsername)
Note, however, that this is insecure as anyone can edit the HTML to manipulate this field. If you need security, you're either going to have to hash/encrypt it or retrieve it from the database again.
Upvotes: 1
Reputation: 33139
You can use hidden fields to show MVC that you are retaining the old values, like so:
@Html.HiddenFor(x => x.Backupsomething)
Upvotes: 2
Reputation: 18411
I usually create hidden fields:
@model SomeController.AccountModel
@using (Html.BeginForm("Update", "SomeController", FormMethod.Post)) {
@Html.HiddenFor(u => u.backupUsername)
@Html.LabelFor(u => u.Username)
@Html.TextBoxFor(u => u.Username)
This way you fill the field when the page loads but it is not changed by the user, so it is passed as is in the post.
Upvotes: 1