Html.Dropdownlist values when using repository classes
Until now I have used the Model class to embed list of related values to render as 开发者_StackOverflow社区DropDownList in the view. For example, suppose I have a Contact model class that has a ContactType property in it
public class Contact {
...
public int ContactTypeID { get; set; }
...
}
ContactTypeID reference a row in a database table that contains all the contact types like Customer, Supplier, etc. I have used successfully until now a property of the Contact class called, for example, ContactTypeList as in the following sample
public IEnumerable<SelectListItem> ContactTypeList {
get {
return GetContactTypeList().Select(
t => new SelectListItem { Text = t.Description,
Value = t.ContactTypeID.ToString() });
}
}
This way when using strong typed views I can do the following way
<%: Html.DropDownListFor( model => model.ContactTypeID, Model.ContactTypeList, new {} )%>
This method works wothout any problem but is not completely clean from the SoC point of view.
In a new project I am starting I am using the repository pattern and StructureMap as the DI/IoC tool and so the model class, does not have anymore a reference to the repository class that is getting the data from the underlying data store.
I know that I can always use the controller and the ViewData/ViewBag to get these lists to pass in the views but I was wondering if this is a good way to achieve the scope.
How are you doing in your projects? What is the best way to achieve the result and having the code remain clean?
Thanks for helping
In our project we also use ViewData to store the list and use them in the view, there's nothing wrong in it.
In my projects I use view models and the controller to manipulate the model:
Model:
public class ContactViewModel
{
public int ContactTypeID { get; set; }
public IEnumerable<SelectListItem> ContactTypeList { get; set; }
}
Controller:
public class ContactsController
{
private readonly IContactsRepository _repository;
public ContactsController(IContactsRepository repository)
{
_repository = repository;
}
[AutoMap(typeof(Contact), typeof(ContactViewModel))]
public ActionResult Index()
{
var model = _repository.GetContacts();
return View(model);
}
}
The AutoMap
attribute used there is an action filter which will execute after the controller action and it will use AutoMapper to replace the model passed to the view (Contact) with the corresponding view model (ContactViewModel
). You may see it in action in a sample project structure I wrote.
Now obviously if you are going to show this contacts drop down list all over your project it deserves a separate controller and a child action which will be reused across your view with the Html.Action helper.
精彩评论