2009-05-19 116 views
2

我是一個MVC新手,所以你將不得不原諒我想象的是一個基本問題。MVC自定義viewmodel問題

我爲了在我的形式的多選列表中創建自定義視圖模型:

public class CustomerFormViewModel 
{ 
    public Customer Customer { get; private set; } 
    public MultiSelectList CustomerType { get; private set; } 

    public CustomerFormViewModel(Customer customer) 
    { 
     Customer = customer 
     // this returns a MultiSelectList: 
     CustomerType = CustomerOptions.Get_CustomerTypes(null); 
    } 
} 

我發現,我的第一次嘗試只捕獲的多選的第一個值,我猜這是因爲我的創建操作是這樣的:

// GET: /Buyer/Create 
    public ActionResult Create() { ... } 

    // POST: /Buyer/Create 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(Customer customer) { ... } 

所以,我決定把它改成這樣:

// GET: /Buyer/Create 
    public ActionResult Create() { ... } 

    // POST: /Buyer/Create 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(CustomerFormViewModel model) { ... } 

這樣我就可以從MultiSelectList中獲得完整的輸出並相應地解析它。麻煩的是,這個抱怨說viewmodel沒有無參數的構造函數(而且沒有) - 我不確定正確的方法去解決這個問題。我已經嘗試過的任何東西都沒有問題,我真的需要一些幫助

萬一有幫助,我的看法是這樣的:

<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MySite.Controllers.CustomerFormViewModel>" %> 
... 
<% using (Html.BeginForm()) 
    <%= Html.ListBox("CustomerType", Model.CustomerType)%> 
... 

回答

1

我相信我得到了它:

public class CustomerModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var form = controllerContext.HttpContext.Request.Form; 

     Customer customer = base.BindModel(controllerContext, bindingContext) as Customer; 

     if (customer!= null) 
     { 
      customer.CustomerType= form["CustomerType"]; 
     } 

     return customer; 
    } 
} 

隨着在Global.asax文件的的Application_Start一個條目() :

 ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder()); 

它將列表框選擇的逗號分隔列表放在字段中。例如「1,3,4」。

1

您是否嘗試過定製ModelBinder的。不知道我認清你的代碼,但是這可能是你的出發點:

public class CustomerFormViewModelBinder : DefaultModelBinder 
{ 
    protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 
    { 
     var model = new CustomerFormViewModel(customer) 
    } 
} 
+0

一直在做一些研究,並得出結論 - 正如你所說 - 一個自定義模型綁定器正是我所需要的。現在我只需要弄清楚如何寫一個! 感謝您的評論 - 我會採納您的建議,看看我能否實現它。 – user101306 2009-05-19 18:15:28