-1

I have a model,

public class Customer
{
 public string Name { get; set;}
 public string CountryCode { get; set;}
}

In the controller

var model = new List<Customer> 
{ 
    new Customer { Name = "foo", CountryCode = "US"},
    new Customer { Name = "bar", CountryCode = "UK",
};          
return PartialView("_Edit", model);

An extension method for displaying all countries:-

public class CountryList
{
public static IEnumerable<SelectListItem> CountrySelectList
    {
        get
        {
            var list = new List<SelectListItem>()
            {
                new SelectListItem { Value = "US", Text="US" },
                new SelectListItem { Value = "UK", Text="UK" },
            };

            return list;
        }
    }
}

In the PartialView

@model List<Customer>

@Html.DropDownListFor(model => model[i].CountryCode, CountryList.CountrySelectList, "Select Country Type")

But the drop down doesn't select each customer's country code? Any thoughts?

PS: It is using model[i] => which is of type Customer, for simplicity i had removed the forloop before rendering the html tags.

@using(Html.BeginForm())
{
   for(int i = 0; i < Model.Count(); i++)
   {
      @Html.TextBoxFor(model => model[i].Name)
      @Html.DropDownListFor..........
   }
}
parsh
  • 746
  • 1
  • 10
  • 23
  • A closer look would have made you understood my question in the first place. model[i] does mean that the razor view is using IEnumerable or IList, my first edit was my mistake, second/third edit was to make it more clearer. – parsh Jun 04 '13 at 17:36

1 Answers1

1

Because your CoutryList helper does returns a list of SelectListItems that all have Selected property set to False (which is default).

I would rewrite your helper method as follows:

public static IEnumerable<SelectListItem> CountrySelectList(string selectedCountryCode)
{
    get
    {
        var list = new List<SelectListItem>()
        {
            new SelectListItem { Value = "US", Text="US" },
            new SelectListItem { Value = "UK", Text="UK" },
        };

        var selectedListItem = list.FirstOrDefault(t=>t.Value== selectedCountryCode);

        if(selectedListItem!=null)
          selectedListItem.Selected=true;


        return list;
    }
}

In view:

@Html.DropDownListFor(model => model[i].Customer, CountryList.CountrySelectList(model[i].Customer.CountryCode), "Select Country Type")
dksh
  • 184
  • 1
  • 6
  • Let me get this correct, you want me to change the property to a method? And I don't think you can access model[i] outside the Func expression. Please let me know if there was any typo? – parsh Jun 04 '13 at 17:32
  • Yep, it is a typo, you would have to change `@Html.DropDownListFor(model => model[i]CountryCode, CountryList.CountrySelectList(Model[i].CountryCode), "Select Country Type")` **CountrySelectList(Model[i]** – parsh Jun 04 '13 at 17:53