简体   繁体   中英

MVC3 Can't get model back to the controller

I have the following 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. How can I change my view to return the list of CheckBoxList? Trying @Html.HiddenFor(m => m.checkBoxList) did not work for me

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM