Loss of ViewModel data after POST
I don't see this problem too often, but I have a .cshtml that uses layout. In the layout I have:
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "someCssClass", @id = "UserForm" }))
{
...rest of the code
}
My main .cshtml using this layout has a model defined at the top, as we always do:
@model CarViewModel
@{
Layout = "~/Views/Shared/_CarLayout.cshtml";
}
When it goes back to my action method, I get zeros for all model values:
public ActionResult Cars(CarViewModel model)
{
carBL.RemoveCars(model.CarIds, model.DealerId);
...
}
Not sure what I need to do here and why this is happening. I usually just return it using autobind. It seems to me when the model is used with RAzor in the markup that comes back with the returned ViewModel, but if I don't use those fields it doesn't ... so I guess it works, and if I don't use them in the markup, do I need to send them back as hidden values ββto force persistence, since I am not using the x fields from the ViewModel (which would automatically save those fields if I used them in the form)?
If the values ββare not bound to the form field, they will fall back to zero.
in the form use below for things like id fields.
@Html.HiddenFor(x => x...)
A quick test to check if the form was submitted correctly would be to change the signature of your action:
public ActionResult Cars(FormCollection form)
{
...
}
If form
not completed, you have a problem with the form post. As a side note, you can accomplish this when viewing the form post data with a tool like FireBug, Chrome Dev Tools, or Fiddler if you prefer.
If the form is submitting correctly, then I have to check that the name of the input fields on the form matches the names CarViewModel
you expect.
Not sure if this has been resolved yet, but this is how I do it (partial code):
@model MyProject.ViewModels.MyViewModel
@using (Html.BeginForm())
{
<table>
<tr>
<td>First Name:</td>
<td>@Html.TextBoxFor(x => x.FirstName, new { maxlength = "50" })
@Html.ValidationMessageFor(x => x.FirstName)
</td>
</tr>
</table>
<button id="btnSave" type="submit">Save</button>
<button id="btnCancel" type="button">Cancel</button>
}
Then my action method to handle the HTTP post request:
[HttpPost]
public ActionResult Create(MyViewModel viewModel)
{
// Check for null on viewModel
// Do what needs to be done
}
Doing it this way should not allow you to lose your form / submission filled values.