Pass IEnumerable list to controller

纵饮孤独 提交于 2020-01-10 05:31:27

问题


In my asp.net MVC 4 project, I'm trying to pass IEnumerable list from view to controller. The problem is that the list receiverd in the action is null. Any help please.

This is part of my code

view :

@model IEnumerable<PFEApplication.Models.agent>
<div id="Leader"> 
@using (Ajax.BeginForm("AddNewLeader", "Equipe", FormMethod.Post, new AjaxOptions {
                    UpdateTargetId = "Leader",
                    HttpMethod = "Post",
                    InsertionMode = InsertionMode.Replace
                    }))
  {
    foreach (var item in Model)
    {
       @Html.HiddenFor(modelItem => item.ID_agent)
       @Html.RadioButtonFor(modelItem => item.SelectedAgent, item.ID_agent)           

       @Html.DisplayFor(modelItem => item.nom_agent) 
       @Html.DisplayFor(modelItem => item.prenom_agent)           
        <br />           

      }
      <br />
     <input type="submit" value="Save" />
     } 
     </div>

Controller :

     public ActionResult AddNewLeader(IEnumerable<agent> ListAgent) 
    {        
            [...]
            if(ListAgent!=null)
            foreach (var ag in ListAgent) {
                if (ag.SelectedAgent != 0) { Id = ag.SelectedAgent; }
            }
            agent agentRemplace = db.agents.Single(a => a.ID_agent == Id);                    
            db.SaveChanges();               

        return PartialView("exitAddNewLeader");
    } 

回答1:


The problem is in fact that this expression:

@Html.HiddenFor(modelItem => item.ID_agent)

and similar as well cannot derive a correct name for the HTML input control, and the resulting request parameters are not parsed by model binder. Usually this is fixed by replacing foreach with for:

@fore (int i=0; i<Model.Count; i++)
{
   @Html.HiddenFor(modelItem => modelItem[i].ID_agent)
   @Html.RadioButtonFor(modelItem => modelItem[i].SelectedAgent, modelItem[i].ID_agent)           

   @Html.DisplayFor(modelItem => modelItem[i].nom_agent) 
   @Html.DisplayFor(modelItem => modelItem[i].prenom_agent)           
    <br />           

}

Note that you would need your view to be typed with IList<> or an array to allow this behavior.



来源:https://stackoverflow.com/questions/23299016/pass-ienumerable-list-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!