Akim Khalilov
Akim Khalilov

Reputation: 1039

ASP.NET MVC 3 dropdown binding

I encountered the next indexer syntax during binding my model with collection to view.

Here is what I have:

public class CustomerModel
{
    public List<Customer> Customers { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ImportAction ImportAction { get; set; }
}

public enum ImportAction
{
    Skip,
    Add,
    Merge
}

My view:

@using (Html.BeginForm("Edit", "Home"))
{
    var index = 0;
    foreach (var customer in Model.Customers)
    {
        <span>Name: @customer.Name</span>
        @Html.DropDownListFor(x => x.Customers[index].ImportAction, customer.ImportAction.ToListItems())
        index++;
    }
    <button type="submit">
        Submit</button>
}

How to avoid this [index] usage? Any other correct syntax? Take to the look, that without it @Html.DropDownListFor would not work and update my model on post back.

Upvotes: 0

Views: 161

Answers (1)

Chad Kapatch
Chad Kapatch

Reputation: 585

you can use the loop variable 'customer' like the following:

@Html.DropDownListFor(x => customer.ImportAction)

Upvotes: 1

Related Questions