我有一个视图模型,我正在创建一个获取操作,
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());
}
在视图模型中,我有一个定义为CustomerNames的选择列表,我希望能够使用该选择列表插入CustomerId值(也在视图模型中定义),该值取自客户表,这是一个独立但相关的实体,
有没有人可以帮助我如何在控制器中设置选择列表以接收来自客户实体的CustomerNames列表?
我的视图抛出一个异常,当我改变它的声明接受视图模型,
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'.
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);
}
内视图
@Html.DropDownListFor("CustomerNames")