Reputation: 1427
I am working with some business objects that relate to one another through their properties. For instance I am loading an "Entry" object from the data store and relating it to "User" objects through the Author and Editor properties.
class Entry{
public User Author { get; set; }
public User Editor { get; set; }
}
class User{
public string Username { get; set; }
}
When I create a new Entry object using MVC2, I want to supply a drop down that has a list of the available users. I am lost as to what way would be best.
Right now I am going down the path of using EditorFor calls, but it has its issues. For example, I can do the following:
<%= Html.EditorFor(model => model.Author) %>
And then create an view control under Shared/EditorTemplates that presents it as a dropdown (possible?) but this seems like it would corrupt all edits of the User class. For instance if I attempt to edit a User object directly, I want to be able to update the fields associated with that class. So I need the editor templates to be context sensitive.
I also attempted to go down the route of manual form creation:
<%= Html.DropDownFor(model => model.Author, (IEnumerable<SelectListItem>)ViewData["Users"]) %>
But this seemed messy and I am confused as to how the values get serialized back into a User object from SelectListItem.
Any help is appreciated. I am sure this problem has been covered before, but I had trouble getting much of any information out of my queries.
Upvotes: 1
Views: 574
Reputation: 34810
I recommend strongly-typed Views and EditFor. It's much easier to maintain and test.
It sounds like you need to start using ViewModels. ViewModels are an abstraction between the View and the Model, so that the View does not interact directly with the Model, which can lead to issues as you have discovered.
A ViewModel is sometimes just a "wrapper" around the actual Model. Using your Entry class as an example, a ViewModel for that might be EntryViewModel
. It could have an Entry
property, as well as supporting related data you want to display. The important thing is that the ViewModel contains only data need by the View it supports, nothing more.
Suppose you wanted users to be able to update the Entry.Author
property from the Entry View- you could populate the EntryViewModel
with a list of IDs and names from the Authors
entity/table.
Upvotes: 2