[英]MVC3 Can't get model back to the controller
我有以下ViewModel
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)
對我不起作用
我想你這樣
@using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
@Html.CheckBoxFor("Model.CheckBoxItem[" + i + "].Checked" , m => m.CheckBoxList[i].Checked)
@Html.DisplayFor("Model.CheckBoxItem[" + i + "].Text",m => m.CheckBoxList[i].Text)
}
檢查復選框輸入名稱在呈現的html中的方式,並檢查表單操作是否正在發送到相應的控制器/操作,方法是否為post
它應該很簡單..將動作參數創建為與“名稱”屬性形式復選框名稱相同的數組
像這樣的東西
[HttpPost]
public ActionResult Delete(int[] checkName)
{
}
嘗試將鏈接添加為隱藏字段: @Html.HiddenFor(m => m.CheckBoxList[i].Link )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.