Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing ViewModel Data after POST

I don't see this problem too often but I've got a .cshtml that uses a layout. In the layout I've got:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "someCssClass", @id = "UserForm" }))
{
      ...rest of the code
}

My main .cshtml using this layout has the model defined at the top as we always do:

@model CarViewModel 
@{
    Layout = "~/Views/Shared/_CarLayout.cshtml";
}

When It gets back to my action method, I get nulls for all values of the model:

public ActionResult Cars(CarViewModel model)
{
    carBL.RemoveCars(model.CarIds, model.DealerId);
    ...
}

Not sure what I need to do here and why this is happening. Usually I just get it back successfully via autobind. It seems to me when the model is used via RAzor in the markup- that gets posted back fine with the returned ViewModel but if I'm not using those fields, it doesn't...so I assume that's how that works and if I don't use them in mark-up I need to send them back as hidden values then to force the persistence since I am not using x fields from the ViewModel (Which would have automatically persisted those fields if I had used them in the form)?

like image 340
PositiveGuy Avatar asked Mar 19 '12 23:03

PositiveGuy


1 Answers

If the values are not bound to a form field, they will come back null.

in the form use the below for things like ID fields.

@Html.HiddenFor(x => x...)
like image 115
TheRealTy Avatar answered Oct 20 '22 00:10

TheRealTy