2012-09-06 19 views
8

Hier ist mein Modell:ASP.NET MVC Modell Liste Bindung

public class Items 
    { 
     public string Foo { get; set; } 
     public string Bar { get; set; } 
    } 

Controller:

public ActionResult Index() 
    { 
     var model = new List<Items> 
         { 
          new Items 
           { 
            Foo = "foo", 
            Bar = "bar" 
           }, 
          new Items 
           { 
            Foo = "ai", 
            Bar = "ia" 
           }, 
          new Items 
           { 
            Foo = "one", 
            Bar = "two" 
           } 
         }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(List<Items> model) 
    { 
     return View(model); 
    } 

anzeigen (Index):

@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < Model.Count; i++) 
    { 
     <div onclick="$(this).remove();"> 
      @Html.TextBoxFor(model => model[i].Foo) <br/> 
      @Html.TextBoxFor(model => model[i].Bar) 
     </div> 
    } 
    <div> 
     <input type="submit"/> 
    </div> 
} 

I zweites Paar löschen:

<div onclick="$(this).remove();"> 
     <input name="[0].Foo" type="text" value="foo"> <br> 
     <input name="[0].Bar" type="text" value="bar"> 
    </div> 

    <div onclick="$(this).remove();"> 
     <input name="[2].Foo" type="text" value="one"> <br> 
     <input name="[2].Bar" type="text" value="two"> 
    </div> 

Beim Posten bekomme ich nur das erste Paar ("foo" und "bar"). Das liegt daran, dass das dritte Paar den Index "2" hat. Ich möchte beide Paare erhalten (nicht mit FormCollection. Ich möchte, dass es automatisch bindet). In Wirklichkeit habe ich viele andere Eingaben in Form, also möchte ich Indizes nicht zu jedem Eingang neu laden und wieder anbringen. Kannst du mir helfen?

+0

Haben Sie das generierte HTML überprüft und überprüft, ob die erwarteten Eingabefelder innerhalb des Formularbereichs liegen? –

+0

Ich habe HTML generiert und ja, es ist in Form. siehe "Ich lösche zweites Paar:" Abschnitt – karaxuna

Antwort

3

I-Lösung gefunden, dank Amit Prajapati:

@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < Model.Count; i++) 
    { 
     var identifier = Guid.NewGuid(); 
     <div onclick="$(this).remove();"> 
      @Html.Hidden("Index", identifier) 
      @Html.TextBox("[" + identifier + "].Foo") 
      <br/> 
      @Html.TextBox("[" + identifier + "].Bar") 
     </div> 
    } 
    <div> 
     <input type="submit" /> 
    </div> 
}