2012-03-26 47 views
0

我有以下視圖模型MVC3不能領型回控制器

public class RecommendationModel 
{ 
    public List<CheckBoxItem> CheckBoxList { get; set; } 

} 

public class CheckBoxItem 
{ 
    public string Text { get; set; } 
    public bool Checked { get; set; } 
    public string Link { get; set; } 
} 

用下面查看

model Sem_App.Models.RecommendationModel 

@using (Html.BeginForm()) 
{ 
     for (int i = 0; i < Model.CheckBoxList.Count(); i++) { 
     @Html.CheckBoxFor(m => m.CheckBoxList[i].Checked) 
     @Html.DisplayFor(m => m.CheckBoxList[i].Text)     
} 
<input type="submit" value="Add To Playlist" /> 
} 

用下面控制器動作

//get 
public ActionResult Recommendation() 
{ 
    RecommendationModel model = new RecommendationModel(); 
    model.CheckBoxList = new List<CheckBoxItem>(); 
    return PartialView(model); 
} 

//post 
[HttpPost] 
public ActionResult Recommendation(RecommendationModel model) 
{ 
     foreach (var item in model.CheckBoxList) 
     { 
      if (item.Checked) 
      { 
       // do something with item.Text 
      } 
     } 
} 

問題是每當我選擇一些項目,然後按提交按鈕返回的模型將CheckBoxList視爲空。我怎樣才能改變我的觀點來返回CheckBoxList的列表?試圖 @Html.HiddenFor(m => m.checkBoxList)我沒有工作

回答

0

嘗試添加鏈接爲一個隱藏字段:@Html.HiddenFor(m => m.CheckBoxList[i].Link)

+0

奏效!但現在我得到我的控制器中的CheckBoxItem.Link和CheckBoxItem.Text空值有什麼想法?我更新了我的控制器 – user972616 2012-03-26 01:03:30

+0

查看「DisplayFor」輸出的HTML,[此方法呈現表示屬性值的字符串。](http://msdn.microsoft.com/zh-cn/library/ee407390%28v = vs.98%29.aspx)當您POST表單時,此值不會像其他表單輸入(和隱藏字段)一樣發送回控制器。 MVC需要從這篇文章中的已知數據重建模型......請記住,MVC是無狀態的(再見viewstate)。 – felickz 2012-03-26 04:19:05

0

選中複選框,輸入名稱是如何在呈現的HTML,並檢查表單動作發送到corrent控制器/動作和方法後

它應該是很簡單..創建操作PARAM爲陣的「名」的同名屬性窗體複選框,輸入

像這樣

[HttpPost] 
    public ActionResult Delete(int[] checkName) 
{ 

} 
1

我想你的東東像這樣

​​