I have a webforms project and I’m using the new Model Binding on ASP.NET 4.5. I have a strongly typed FormView on my page that contains a DropDownList that will allow the user to select a related entity (think Product -> Category).
Is there a way to set this up so that, on my InsertMethod, I can get direct access to the related entity (Product.Category, for example)? I need to check some validation rules on the related entities, and the only way I found to do that was to set up my DropDownList to return the Id of the related record, and then fetch it from the database. That seems rather inefficient.
Edit: Damn, no one huh!? Well, that’s what you get for being an early adopter of new technologies! 😀
I had the same issue on MVC, the best solution I have found was to use the ForeignKey data annotation on my model, this way I could insert only the related object’s ID and retrieve the object later. Here’s an example:
Now, it’s been ages since I last used WebForms so I don’t really know how to bind the categories list to the DropDownList, maybe something like this:
And maybe when you get your product back on your Create or Update method, it will come with the CategoryId property properly attributed, and then all you’ll have to do is save the EF’s context. Good luck.