[英]MVC3 Can't get model back to the controller
I have the following ViewModel 我有以下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; }
}
With the following View 具有以下视图
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" />
}
With the following controller actions 通过以下控制器动作
//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
}
}
}
Problem is whenever I select some items and press the submit button the model returned has CheckBoxList as empty. 问题是,无论何时我选择一些项目并按提交按钮,返回的模型的CheckBoxList都为空。 How can I change my view to return the list of CheckBoxList? 如何更改视图以返回CheckBoxList列表? Trying @Html.HiddenFor(m => m.checkBoxList)
did not work for me 尝试@Html.HiddenFor(m => m.checkBoxList)
对我不起作用
I think you nee something like this 我想你这样
@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)
}
Check how the checkbox input name is in the rendered html and also check the form action is sending to the corrent controller/action and the method is post 检查复选框输入名称在呈现的html中的方式,并检查表单操作是否正在发送到相应的控制器/操作,方法是否为post
it should be something very simple.. create the action param as array with the same name of the "name" attribute form check box input 它应该很简单..将动作参数创建为与“名称”属性形式复选框名称相同的数组
something like this 像这样的东西
[HttpPost]
public ActionResult Delete(int[] checkName)
{
}
尝试将链接添加为隐藏字段: @Html.HiddenFor(m => m.CheckBoxList[i].Link )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.