2011-08-02 74 views
1

我視圖模型,我在創建取得動作很contructing將數據傳遞給選擇列表,MVC3&EF4如何使用視圖模型

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選擇列表,我希望能夠使用該選擇列表來插入客戶表中的客戶ID值(也在視圖模型中定義),該客戶表是一個單獨但相關的實體,

任何人都可以請幫助我如何設置選擇列表在控制器中接收來自客戶實體的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'. 

任何幫助/建議表示讚賞。

回答

3
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")