1

I'm using Entity Framework 4 and my model relationships are automatically generated from the lookup table. My models consist of Request and Building. A request can have many buildings, and a building can be associated with many requests. I've found a few posts on how DropDownFor automatically selects an item based on model relationships. But the HtmlHelper CheckBoxFor wants an expression that returns bool. My models don't have a bool indicating checked because it is based on the relationship.

Anyone have tips or experience?

1 Answer 1

2

Don't pass your EF models to the view. Define view models which are classes specifically tailored to the needs of a given view. You don't need many-to-many recursive relations in the view. So in the case where you want to generate a checkbox you would have a corresponding boolean property on your view model. It's the controller that would query the repository, fetch the EF models, map them to the view model (this task could be simplified with frameworks such as AutoMapper) and finally pass the view model to the view so that in your view you simply:

@Html.CheckBoxFor(x => x.SomeBooleanProperty)

And if you wanted to have a list of checkboxes then your view model would contain a collection property of some type that will hold the boolean property.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Darin! I couldn't seem to get an answer out of anyone if a viewmodel was specifically required or not in this case.
I have an AccessRequestViewModel that contains a RequestDailyViewModel. I have my controller creating the AccessRequestViewModel and I was planning on setting the map up in its constructor method to map between an EF Request model and my app's RequestDailyViewModel. Would you say this should strictly be done in the controller or for complicated types is this ok to be handled from within the single "parent" view model?
@ryan: I have a similar challenge, and I've had success with populating the viewmodel as Darin suggests. However, I can't get the collection to model-bind back to the HttpPost Action Method -- have you had similar problems? Did you have to resort to a custom model binder for this?
I have the same problem as Ryan, however I am new enough to ViewModels and C# that I don't understand the answer provided. @Darin any chance you can provide some code regarding how this might look in both the model and controller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.