I can't figure out how to have navigation properties for my model (EF4) not be null after I post. I have the same problem on several basic pages.
i.e. I have a table Estimate with a foreign key of LoginID (from the Login table).
In my HTTPGet Edit method, I find the specific estimate I want:
Estimate estimate = db.Estimates.Find(id)
From here I can access the Login navigation property and any of the properties of that record from the Login table.
I pass this estimate as the model for my strongly typed view. When my HTTPPost Edit method gets called (and the model is passed to it as a parameter), my Login navigation property is null and I can't access anything in it. I can get around it of course because I do have the LoginID field in my estimate class, but it feels really clunky and like I'm missing out on a key benefit of the entity framework.
I have this same problem on multiple pages where I'm passing a model with a navigation property to my view and the view is returning the model with a null navigation property.
Below is an example of the code I was having trouble with:
[HttpPost]
public ActionResult Edit(Estimate estimate)
{
var test = estimate.Login.CompanyProfileID;
...
I can access Model.Login and all of it's properties just fine in the view, so I know it's getting passed to the view properly. It just doesn't pass the navigation property back to the controller when my form submits.
What is happening is that MVC uses something called 'Model Binding', which matches all the fields that POST passes in the page request to matching properties of the parameter of your action.
So, if the property is not included in the input fields in the POST
page, it will not be bound to the parameter in your POST
action, and thus, will be null.
So, you could either include a hidden field for every property in Login
, e.g.
@Html.HiddenFor(m => m.Login.ID)
@Html.HiddenFor(m => m.Login.Name)
Or, just do as you describe in your workaround - ie requery the database based on the Id. Although this may seem clunky, this is a perfectly valid way of doing things, as it avoids having to pass hidden fields around all over the place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With