2014-02-06 76 views
0

我有一個視圖模型,並在裏面存在一個列表。當我通過發佈將數據發送給控制器時,列表爲空。查看模型列表屬性來自post方法null null

有什麼問題?

查看:

@model MyProject.ViewModel.MyViewModel 

@{ 
    var grid = new WebGrid(Model.MyList); 
} 

@using(Html.BeginForm()) 
{ 
    @grid.GetHtml(columns: grid.Columns(grid.Column(header: "Column", format: @<text><input name="Add" type="checkbox" @(item.Checked == true ? "Checked" : null) />@item.Name</text>))) 

    <button type="submit">Send</button> 
} 

控制器:

[HttpPost] 
public ActionResult MyMethod(MyViewModel viewModel) 
{ 
    // In this point, my list is comming null. 
    return View(); 
} 

視圖模型:

public class ObjectModel 
{ 
    public string Name { get; set; } 
    public bool Checked { get; set; } 
} 

public class MyViewModel 
{ 
    public MyViewModel() 
    { 
     this.MyList = new List<ObjectModel>(); 
    } 

    public List<ObjectModel> MyList { get; set; } 
} 
+1

的問題是,剃刀引擎只做數據的HTML輔助綁定,所以你既然是使用WebGrid它不會自動執行。你可能想看看這個類似的問題:http://stackoverflow.com/questions/15113839/post-items-of-webgrid-asp-net-mvc3 – SOfanatic

+0

嗨,感謝您的幫助!是工作! –

回答

0

你的問題是,提交默認模型聯編程序後無法正確綁定您的數據。爲了能夠這樣做,你的輸入內容都必須包含適當的語法它的名稱屬性中,某事像:

<input name="MyList[0].Name" 
<input name="MyList[1].Name" 
//and so on 

有一個其實你挑戰了幾個解決方案。我個人會創建我自己的自定義綁定,然後遍歷FormCollection。爲了能夠區分不同的項目之間distinquish你就必須改變這種部分:

<input name="Add" 

到:

<input name="Add" value="@item.Name" 

然後你定製綁定看起來是這樣的:

public class MyViewModelBinder: IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, 
          ModelBindingContext bindingContext) 
    { 
     HttpRequestBase request = controllerContext.HttpContext.Request; 

     List<ObjectModel> list = new List<ObjectModel>(); 
     var ids= form.GetValues("Add"); 
     //in your case your ids would be the names of your items 
     foreach (var id in ids) 
     { 
      list.Add(new ObjectModel(){ Name = id, Checked= true}); 
     } 

     return new MyViewModel 
        { 
         MyList = list 
        }; 
    } 
} 

最後你應該將此添加到您的模型粘合劑的全局集合中:

protected void Application_Start() 
{ 
    // some configuration code 
    ModelBinders.Binders.Add(typeof(MyViewModel), new MyViewModelBinder()); 
} 

你可以將它設置爲默認的模型綁定您MyViewModel或只需添加這MyMethod行動:

[HttpPost] 
public ActionResult MyMethod 
    ([ModelBinder(typeof(MyViewModelBinder))]MyViewModel viewModel) 
{ 
    // In this point, your list will not come null 
    return View(); 
}