1
votes

I've tried to populate a dropdownlist with a viewModel passed from a controller with the main goal of setting a selected attribute tag, so that when the dropDown-list loads a specific item in the dropdown-list is selected. I'm using MVC 5 with Razor.

There are many question related to DropDownListFor but unfortunately I haven't found what I'm looking for.

  1. I've found many solutions that work with viewbags, but I this is not what I'm looking for, I want to populate the dropdown-list through a strongly typed model.
  2. The Html helper I want to use is @Html.DropDownListFor (not @Html.DropDownList). From what I know helpers postfixed with For are overloaded with linq expressions, they are used to deal with models and are strongly typed, while the non postfixed For are used with viewbags.

This is what it should look like, the default city selected should be "Monza"

enter image description hereenter image description here

At the moment I've managed to achieve this result only with @Html.DropDownList, as said before this is not my intention I want to achieve the same result with @Html.DropDownListFor. For the sake of documentation this is the code:

This approach uses @Html.DropDownList

MODEL

public class City
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CityId { get; set; }
    public int ProvinceId { get; set; }
    [Display(Name = "Città")]
    public string Name { get; set; }
    [Display(Name = "CAP")]
    public string ZipCode { get; set; }
    public int Dispose { get; set; }

    public virtual Province Province { get; set; }
}

VIEW MODEL

public class AccountIndexGetVM
{
    public UserData userData = new UserData();
    public AddressUser addressUser = new AddressUser();
    public IEnumerable<SelectListItem> cities { get; set; } //<--Cities to DDL
}

CONTROLLER ACTION

//Populating data to the view model and send to view            
accountIndexGetVM.userData = userData;
accountIndexGetVM.addressUser = addressUser;
accountIndexGetVM.cities = new SelectList(db.Cities, "CityId", "Name", addressUser.City.CityId.ToString()); 
return View(accountIndexGetVM);

VIEW creating dropdown-list in

@using MyProject.ViewModels.Account
@model AccountIndexGetVM
//some code...
<td>@Html.LabelFor(m => m.addressUser.City.Name)</td>
<td>@Html.DropDownList("CityAttributeIDVAlue", Model.cities, "Please Select a City")</td>

HTML SOURCE CODE RESULT

<td><select id="CityAttributeIDVAlue" name="CityAttributeIDVAlue"><option value="">Please Select a City</option>
<option value="277">Aosta</option>
<option value="4156">Meda</option>
<option value="4175">Melegnano</option>
<option value="4310">Milano</option>
<option selected="selected" value="4750">Monza</option> <!--Selected is PRESENT-->
</select></td>

This approach uses @Html.DropDownListFor

enter image description hereenter image description here

As you can see the default selected ddl item is not select, instead the optional ("Please select a city") is selected. This is not my intention, "Monza" should be selected when the ddl is loaded and a selected attribute should be present in the HTML option tag.

The only change I've made is in the view, this is the code, and used the DropDownListFor helper:

VIEW

    <td>@Html.LabelFor(m => m.addressUser.City.Name)</td>
    <td>@Html.DropDownListFor(m => m.cities, (IEnumerable<SelectListItem>)Model.cities, "Please Select a City")</td>

HTML GENERATED

<td><select id="cities" name="cities"><option value="">Please Select a City</option>
<option value="277">Aosta</option>
<option value="4156">Meda</option>
<option value="4175">Melegnano</option>
<option value="4310">Milano</option>
<option value="4750">Monza</option>  <!--No selected attribute present-->
</select></td>

Question: Is there a way to use DropDownListFor Html helper to generated a slected tag in the html ddl or the only way to go is DropDownList?

1

1 Answers

0
votes

I'm not sure how Select helpers differ. I passed this list along with the view model.

List<SelectListItem> citySelectList = new List<SelectListItem>();
cityList = cities.GetAll().OrderBy(x => x.DESCRIPTION).ToList();

foreach (var city in cityList)
{
    citySelectList .Add(new SelectListItem() 
    {
        Value = city.ID, 
        Text = city.Desc, 
        Selected = true 
    });
}

Then on the view:

@Html.DropDownListFor(x => x.City, Model.CitySelectList, "", new { id = "citySelectID" })