【问题标题】:MVC3 Can't get model back to the controllerMVC3 无法将模型返回到控制器
【发布时间】:2012-03-26 00:41:22
【问题描述】:

我有以下 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 =&gt; m.checkBoxList) 对我不起作用

【问题讨论】:

    标签: asp.net-mvc-3 model controller


    【解决方案1】:

    我想你需要这样的东西

    @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)                   
    }
    

    【讨论】:

      【解决方案2】:

      尝试将链接添加为隐藏字段:@Html.HiddenFor(m =&gt; m.CheckBoxList[i].Link )

      【讨论】:

      • 成功了!但是现在我的控制器中出现了 CheckBoxItem.Link 和 CheckBoxItem.Text 空值,知道为什么吗?我更新了我的控制器
      • 查看“DisplayFor”输出的 HTML,this method renders a string that represents the property value. 当您发布表单时,该值不会像其他表单输入(和隐藏字段)一样发送回控制器。 MVC 需要从这篇文章中的已知数据重建模型......记住 MVC 是无状态的(再见视图状态)。
      【解决方案3】:

      检查复选框输入名称在呈现的 html 中的显示方式,并检查表单操作正在发送到正确的控制器/操作,方法是 post

      应该是很简单的东西.. 将动作参数创建为与“名称”属性表单复选框输入具有相同名称的数组

      类似的东西

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-23
        • 2014-05-20
        • 2019-03-12
        • 2012-04-03
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多