我有以下視圖模型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)
我沒有工作
奏效!但現在我得到我的控制器中的CheckBoxItem.Link和CheckBoxItem.Text空值有什麼想法?我更新了我的控制器 – user972616 2012-03-26 01:03:30
查看「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