Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Pass IEnumerable list to controller

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");
    } 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...