0

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.

1
  • @Html.TextBoxFor(x => x.Products[i].ProductType) display correctly. Commented Feb 11, 2014 at 15:09

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.