Reputation: 10358
Model
public class Customer
{
public string Name {get;set;}
public List<Product> Products {get;set;}
}
public class Product
{
public string Name {get;set;}
public ProductType {get;set;}
public IEnumerable<ProductType> ProductTypeList { get; set; }
}
Controller
[HttpGet]
public ActionResult Index(int id)
{
var customer = GetCustomer(id);
return View(customer);
}
View
@model Customer
@Html.TextBoxFor(x=>x.Name);
@for (int i = 0; i < Model.Products.Count; i++)
{
@Html.TextBoxFor(x => x.Products[i].Name)
@Html.TextBoxFor(x => x.Products[i].Price)
@Html.DropDownListFor(x => x.Products[i].ProductType, Model.ProductTypeList)
}
Result:
The name and price of the products in HTML are displayed correctly but the <select>
does not have correct ProductType selected (the first item is selected even though model has other value).
When I submit the form the value is bound and when validation return the form is is also bound to selected value.
The only issue is that DropDownList selected value is not bound when the page is loaded first time.
Upvotes: 0
Views: 860
Reputation: 33305
I think the problem lies with the ProductType
:
@Html.DropDownListFor(x => x.Products[i].ProductType, Model.ProductTypeList)
It appears to be a complex type.
Try changing it to this instead:
public class Product
{
public string Name {get;set;}
public string SelectedProductType {get;set;}
public IEnumerable<ProductType> ProductTypeList { get; set; }
}
In the above, SelectedProductType
would be the Id of your ProductType
.
Then setting it like this:
@Html.DropDownListFor(x => x.Products[i].SelectedProductType, Model.ProductTypeList)
Upvotes: 1