DropDownListFor in EditorTemplate not selecting value

asp.net Mvc

asp.net Mvc Problem Overview


I have an editor template for a custom object. Inside that editor template I use a couple of DropDownListFor helpers. In each of them I specify a unique model property (with the pre-selected value) and the select list containing all the select options.

Example:

<%=Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList) %>

I know that the option values are being populated (from viewing source) and that my Model is passed in with the correct ID value (DocumentCategoryType).

When the view is rendered, there is no selected item in my dropdown and therefore it defaults to the first (non-selected) value.

Does anyone have any ideas?

Thanks.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

We also solved the solution by populating a new SelectList that has the appropriate SelectListItem selected, but created this extension method to keep the call to DropDownListFor a little cleaner:

public static SelectList MakeSelection(this SelectList list, object selection)
{
    return new SelectList(list.Items, list.DataValueField, list.DataTextField, selection);
}

Then your DropDownListFor call becomes:

<%= Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList.MakeSelection(Model.DocumentCategoryType)) %>

Solution 2 - asp.net Mvc

Looking through the ASP.NET MVC 2 source code reveals some solutions to this problem. Essentially, any SelectListItem in the SelectList passed in the helper extension method that has the Selected property set to true does not have any bearing over the <option> element rendered with the selected attribute applied for the item.

The selected attribute on <option> elements is determined by

  1. checking that the helper extension method was passed a SelectList. If this is null, the framework will look in the ViewData for a value corresponding to the key that is the view model property for which you wish to render the drop down list for. If the value is a SelectList, this will be used to render the <select> including taking any selected values, so long as the model state for the model property is null.

  2. If a SelectList has been passed in the helper extension method and the model state for the model property is null, the framework will look in the ViewData for a default value, using the model property name as the key. The value in view data is converted to a string and any items in the SelectList passed to the helper extension method that have a value (if no value is set, then the Text will be checked) that matches the default value will have the Selected property set to true which in turn will render an <option> with the attribute selected="selected".

Putting this together, there are two plausible options that I can see to have an option selected and use the strongly typed DropDownListFor:

Using the following view model

public class CategoriesViewModel
{
    public string SelectedCategory { get; private set ; }
    public ICollection<string> Categories { get; private set; }

    public CategoriesViewModel(string selectedCategory, ICollection<string> categories)
    {
        SelectedCategory = selectedCategory;
        Categories = categories;
    }
}

Option 1

Set a value in the ViewData in the controller rendering your view keyed against the property name of the collection used to render the dropdown

the controller action

public class CategoriesController
{
    [HttpGet]
    public ViewResult Select()
    {
        /* some code that gets data from a datasource to populate the view model  */
        ICollection<string> categories = repository.getCategoriesForUser();
        string selectedCategory = repository.getUsersSelectedCategory();

        CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);
        this.ViewData["Categories"] = selectedCategory;        

        return View(model);
    }

    [HttpPost]
    public ActionResult Select(CategoriesViewModel model)
    {
        /* some code that does something */
    }
}

and in the strongly typed view

<%: Html.DropDownListFor(m => m.Categories, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>

Option 2

Render the dropdown using the name of the property of the selected item(s)

the controller action

public class CategoriesController
{
    [HttpGet]
    public ViewResult Select()
    {
        /* some code that gets data from a datasource to populate the view model  */
        ICollection<string> categories = repository.getCategoriesForUser();
        string selectedCategory = repository.getUsersSelectedCategory();

        CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);

        return View(model);
    }

    [HttpPost]
    public ActionResult Select(CategoriesViewModel model)
    {
        /* some code that does something */
    }
}

and in the strongly typed view

<%: Html.DropDownListFor(m => m.SelectedCategory, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>

Solution 3 - asp.net Mvc

It is confirmed as a bug @ aspnet.codeplex.com and only behaves like this for strongly typed views.

Workaround: populate your SelectList in the view code

like

<%= Html.DropDown("DocumentCategoryType", new SelectList(Model.Categories,"id","Name",Model.SelectedCategory")) =>

Solution 4 - asp.net Mvc

Yuck. I ended up solving it like this. I hope this gets fixed for RTM.

   <%if(Model!=null){ %>
        <%= Html.DropDownListFor(m => m.DocumentCategoryType, new SelectList(Model.DocumentCategoryTypeList,"Value","Text", Model.DocumentCategoryType))%>
        <%}else{%>
            <%=Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList) %>
        <%}%>

Solution 5 - asp.net Mvc

Make sure you have a value assigned to m.DocumentCategoryType when you send it to the view.

Generally this value will get reset when you do a post back so you just need to specify the value when returning to your view.

When creating a drop down list you need to pass it two values. 1. This is where you will store the selected value 2. Is the actual List

Example

<%=Html.DropDownListFor(m => m.DocumentCategoryType, Model.DocumentCategoryTypeList) %>

I made the mistake of setting the select list item Selected value to True. This won't do anything. Instead just assign a value to m.DocumentCategoryType in your controller and this will actually do the selection for you.

Solution 6 - asp.net Mvc

Here's another good solution if the source for your drop down list is an IEnumerable instead of a SelectList:

public static SelectList MakeSelection(this IEnumerable<SelectListItem> list, object selection, string dataValueField = "Value", string dataTextField = "Text")
{
	return new SelectList(list, dataValueField, dataTextField, selection);
}

Solution 7 - asp.net Mvc

Model.DocumentCategoryTypeList

This is probably your problem. On the SelectListItems, do you set the value to the .ToString() output?

 var list = new List<SelectListItem>()
                           {
                               new SelectListItem()
                                   {
                                       Value = Category.Book.ToString(),
                                       Text = "Book"                                     
                                   },
                               new SelectListItem()
                                   {
                                       Value = Category.BitsAndPieces.ToString(),
                                       Text = "Bits And Pieces"                            },
                               new SelectListItem()
                                   {
                                       Value = Category.Envelope.ToString(),
                                       Text = "Envelopes"                              }
                           };

Works for me after doing that. It just needs to be able to match the value from the object

Solution 8 - asp.net Mvc

I managed to solve the same problem by saying the folling:

new SelectList(sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text")

This trick is converting to the value to a string. I know this has been mentioned in previous answers but i find my solution a little cleaner :). Hope this helps.

Solution 9 - asp.net Mvc

Copied na pasted from my project:

<%= Html.DropDownListFor(m => m.Profession.Profession_id, new SelectList(Model.Professions, "Profession_id", "Profession_title"),"-- Profession --")%>

Model that is passed:

   ...
            public Profession Profession { get; set; }
            public IList<Profession> Professions { get; set; }
    ...

Html generated:

  <select id="Profession_Profession_id" name="Profession.Profession_id">
    <option value="">-- Profesion --</option>
    <option value="4">Informatico</option>
    <option selected="selected" value="5">Administracion</option>
    </select> 

Works for me. I have this on the form and the only disadvantage is that if model is not valid and I return the model back to the view I have to reload the list of Professions.

obj.Professions = ProfileService.GetProfessions();
return View(obj);

Solution 10 - asp.net Mvc

I also had this problem with a field ProgramName. Turns out we used ViewBag.ProgramName in the BaseController and Layout.cshtml, and this was for a different purpose. Since the value in ViewBag.ProgramName was not found in the dropdownlist, no value was selected even though the SelectListItem.Selected was true for one item in the list. We just changed the ViewBag to use a different key and the problem was resolved.

Solution 11 - asp.net Mvc

Here is a drop-in DropDownListFor replacement that varies only slightly from the original MVC source.

Example:

<%=Html.FixedDropDownListFor(m => m.DocumentCategoryType, 
    Model.DocumentCategoryTypeList) %>

Solution 12 - asp.net Mvc

I was worried about the performance of making so many copies of my selectList, so instead, I added the selectedvalue as a custom attribute, then used jquery to actually perform the item select:

@Html.DropDownListFor(item => item.AttendeeID, attendeeChoices, String.Empty, new { setselectedvalue = Model.AttendeeID })

........


jQuery("select[setselectedvalue]").each(function () { e = jQuery(this); e.val(e.attr("setselectedvalue")); });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkmehtaView Question on Stackoverflow
Solution 1 - asp.net MvcCurtis BuysView Answer on Stackoverflow
Solution 2 - asp.net MvcRuss CamView Answer on Stackoverflow
Solution 3 - asp.net MvcAlexander TaranView Answer on Stackoverflow
Solution 4 - asp.net MvckmehtaView Answer on Stackoverflow
Solution 5 - asp.net MvcBrett AllredView Answer on Stackoverflow
Solution 6 - asp.net MvcMrDustpanView Answer on Stackoverflow
Solution 7 - asp.net MvcDanView Answer on Stackoverflow
Solution 8 - asp.net MvcnfpleeView Answer on Stackoverflow
Solution 9 - asp.net MvcArtur KędziorView Answer on Stackoverflow
Solution 10 - asp.net MvcJeremy MeyerView Answer on Stackoverflow
Solution 11 - asp.net MvcDaveMorganTexasView Answer on Stackoverflow
Solution 12 - asp.net MvcwillmanView Answer on Stackoverflow