MVC3 & EF4 How to pass data to a select list using a viewmodel
I have viewmodel which i am contructing in a Create get action,
public class SiteAdminCreateViewModel
{
public int CustomerId { get; set; }
public string ContactName { get; set; }
[Required(ErrorMessage = "A contact number is Required")]
public string ContactNo { get; set; }
public IEnumerable<SelectListItem> CustomerNames { get; set; }
}
public ViewResult Create(SiteAdminCreateViewModel model)
{
var query = from cs in repository.CustomerSites
select new SiteAdminCreateViewModel
{
CustomerId = cs.Customer.CustomerId,
ContactName = cs.ContactName,
ContactNo = cs.ContactNo,
CustomerNames = ??
};
return View(query.ToList());
}
In the viewmodel i have a select list defined as CustomerNames, i want to be able to use that select list to insert the CustomerId value (also defined in the viewmodel) taken from the Customers table which is a seperate but related entity,
Can anyone please help with how i can set the selec开发者_JAVA技巧t list up in the controller to receive a list of CustomerNames from the Customer entity?
Also my view throws an exception when i change its declaration to accept the viewmodel,
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[CustomerOrders.WebUI.Models.SiteAdminCreateViewModel]', but this dictionary requires a model item of type 'CustomerOrders.WebUI.Models.SiteAdminCreateViewModel'.
Any help/advice is appreciated.
public ActionResult MyController(SiteAdminCreateViewModel model)
{
var query = from cs in repository.CustomerSites
select new SiteAdminCreateViewModel
{
Value= cs.Customer.CustomerId,
Text= cs.ContactName
};
ViewBag.CustomerNames=query.ToList();
return View(model);
}
inside view
@Html.DropDownListFor("CustomerNames")
精彩评论