Alex
Alex

Reputation: 431

Bind model property collections

My scenario is much complicated so i simplified it with the example below. The main problem is binding collection properties of a model, specifying the path of the property like Html.TextBox("List[0].Name") and not the Html.TextBoxFor(t => t.List[0].Name). So, for the current view i will only know some of the metadata of the model so i will have to construct it this way. Here is the scenario :

Model

public class ModelTest
{
    public int Id {get;set;}
    public List<Foo> Collection {get;set;}
}

public class Foo
{
    public string Value1 {get;set;}
    public string Value2 {get;set;}
}

Controller

public class TestController: Controller
{
    [HttpGet]
    public ActionResult Test()
    {
        var model = new ModelTest()
        {
            Id = 455,
            Collection = new List<Foo>()
            {
                new Foo(){ Value1 = "sagasga", Value2 = "Beul"},
                new Foo(){ Value1 = "dgdsgds", Value2 = "fhfhd" }
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Test( ModelTest model)
    {
        //....
        return View();
    }

View:

@using (Html.BeginForm())
{
    @Html.TextBox("Id")
    @Html.TextBox("Collection[0].Value1")
    @Html.TextBox("Collection[0].Value2")
    <input type="submit" value="Add" />
}

For the code above i get empty textboxes for the collection values. However, when the page is submited i get the model built correct in the Post method.

Many thanks, Alex

Upvotes: 1

Views: 459

Answers (1)

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

This is the way to name you input fields when you wanna post a collection to your controller. However, you have to specify the initial value yourself. Your code is currently just creating textbox with the name property set to Collection[0].Value1. You still need to specify the input this way,

@Html.TextBox("Collection[0].Value1", Model.Collection.FirstOrDefault().Value1)
@Html.TextBox("Collection[0].Value2", Model.Collection.FirstOrDefault().Value2)

Upvotes: 3

Related Questions