Here is my model:
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);
}
View (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 delete second pair:
<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>
When posting, i get only first pair ("foo" and "bar"). It's because third pair has index "2". I want to get both pairs(Not using FormCollection. I want it to bind automatically). In reality, I have many other inputs on form, so i don't want to reload and reattach indices to each input. Can you help me?
What Is Model Binding? ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
asp.net mvc supports data binding. You can bind data to some model and post it back when the form is submitted.
This may be helpful to you....
need to place Hidden field on each item...
MVC3 Non-Sequential Indices and DefaultModelBinder
I found solution, thanks to 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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With