I’m struggling, a bit, with MVC / Razor / Entity Framework.
I need to create an object which references a parent object. I have a field in my model, called ParentID, but I’m having trouble figuring out how to populate it with the parent’s ID.
I’m thinking I need a hidden-field in my view, and then maybe place the ParentID in the ViewBag, and point that ViewBag property to the hidden field, but I can’t seem to get that to work.
Something like this, was my assumption:
@Html.Hidden("BladeID", ViewBag.ParentBlade)
I’m not sure I’ve explained myself very well, so please ask away, and I’ll expand.
Also, I’m not sure I’m doing this the correct way. This is all very new to me, coming from webforms.
If the
ParentIDis already in the model, why not populate the hidden field directly from there?If you really want to populate it from the
ViewBagyou’ll have tot cast it back toint(assuming that’s the type ofParentID), because theViewBagis of typedynamic:UPDATE based on comments
If your view depends on two (or more) separate model classes you can always opt for creating custom a view model for that view, something like:
and then use that class as the model in your view:
That said, there is, in my opinion, nothing wrong in using the
ViewBagin this case, particularly if all you need is one property.