Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Parent's ID to hidden field

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.

like image 464
Nicolai Avatar asked Jan 17 '23 19:01

Nicolai


1 Answers

If the ParentID is already in the model, why not populate the hidden field directly from there?

@Html.Hidden("BladeID", Model.ParentID)

If you really want to populate it from the ViewBag you'll have tot cast it back to int (assuming that's the type of ParentID), because the ViewBag is of type dynamic:

@Html.Hidden("BladeID", (int)ViewBag.ParentBlade)



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:

public class ParentChildViewModel
{
    public Blade Parent { get; set; }
    public Blade Child { get; set; }
}

and then use that class as the model in your view:

@model ParentChildViewModel
// more view code here
@Html.Hidden("BladeID", Model.Child.ParentID)

That said, there is, in my opinion, nothing wrong in using the ViewBag in this case, particularly if all you need is one property.

like image 197
Sergi Papaseit Avatar answered Jan 30 '23 19:01

Sergi Papaseit