[ACCEPTED]-Set selected value in SelectList after instantiation-selectlist

Accepted answer
Score: 19

I think you are fighting the framework. The 16 data going into your views should be created 15 at the Last Possible Minute (LPM).

Thinking 14 this way, a SelectList is a type to feed the DropDownList HTML 13 helper. It is NOT a place to store data 12 while you decide how to process it.

A better 11 solution would be to retrieve your data 10 into a List<T> and then initialize the SelectList(s) when 9 you need to. An immediate benefit of this 8 practice is that it allows you to reuse 7 your List<T> for more than one DropDownList, such as:

Country of birth
Country of residence

These 6 SelectLists all use the Countries list of type List<Country>.

You 5 can use your List<T> at the 'last minute' like 4 in this example:

public class TaxCheatsFormViewModel
{
    private List<Country> countries { get; set; }

    public TaxCheat Cheat { get; private set; }
    public SelectList CountryOfBirth { get; private set; }
    public SelectList CountryOfResidence { get; private set; }
    public SelectList CountryOfDomicile { get; private set; }

    public TaxCheatsFormViewModel(TaxCheat baddie)
    {
        TaxCheat = baddie;
        countries = TaxCheatRepository.GetList<Country>();
        CountryOfBirth = new SelectList(countries, baddie.COB);
        CountryOfResidence = new SelectList(countries, baddie.COR);
        CountryOfDomicile = new SelectList(countries, baddie.COD);
    }
}

The point being that you 3 should keep your data in a List<T> till you really 2 need to output it; the last possible minute 1 (LPM).

Score: 4

Because this is such a high result in Google, I'm 15 providing what I found to work here (despite 14 the age):

If you are using a Strongly typed 13 View (i.e. the Model has an assigned type), the 12 SelectedValue provided to the Constructor 11 of the SelectList is overwritten by the 10 value of the object used for the Model of 9 the page.

This works well on an edit page, but 8 not for Create when you want to preselect 7 a specific value, so one workaround is simply 6 to assign the correct value on a default 5 constructed object you pass to the view 4 as the Model. e.g.

var model = new SubjectViewModel()
{
   Subject = new Subject(),
   Types = data.SubjectTypes.ToList()
}
model.Subject.SubjectType = model.Types.FirstOrDefault(t => t.Id == typeId);
ViewData.Model = model;
return View();

so the code in my Create 3 View that looks like this:

Html.DropDownListFor(model => model.Subject.SubjectTypeId, new SelectList(model.Types, "Id", "Name"))

returns the Drop 2 Down List with the value I assigned as the 1 SelectedValue in the list.

Score: 4

I know it' an old question, but it might 4 help someone out there. I did what looks 3 to be closely like what Erik did. I just 2 created a new SelectList from my existing 1 one...

SelectList myList = GetMySelectList();
SelectListItem selected = myList.FirstOrDefault(x => x.Text.ToUpper().Contains("UNITED STATES"));
if (selected != null)
{
     myList = new SelectList(myList, "value", "text", selected.Value);
}
Score: 3

The "SelectedValue" property is read-only. Setting 6 it in the constructor is the only way.

Tor, the 5 SelectList is an ASP.NET MVC construct used 4 to create a drop-down list. Doing it your 3 way should work too, but the SelectList 2 should do it for you (and not in JS) if 1 done properly.

Score: 1

I think you can do this in the controller. If 13 you are going to render a drop down list 12 with name/ID StateCode, then you can set 11 the selected state using this code after 10 the SelectList is created:

ViewData["StateCode"] = "VT";

It 9 seems that the drop down list HTML helper 8 looks for a ViewData item with the same 7 name as the drop down list that's being 6 created.

I don't think I like using this 5 technique, but it does seem to work.

I do 4 agree that the SelectList class is a little 3 weak at the moment. I'd like to be able 2 to create a SelectList and then select a 1 value later by either value or text.

Score: 0

You mean client-side, in the browser?

var select = document.getElementById('mySelect');
select.options[newIndex].selected = true;

0

Score: 0

The SelectList object is readonly after 2 it was created. if you want to select something 1 you better do it like:

<%= Html.DropDownList("clientId", ViewData["clients"] as List<SelectListItem>,)%>

And in the code behind:

    ViewData["clientId"] = "ASD"; //This should be the value of item you want to select
    ViewData["clients"] = clientItemList; //List<SelectListItem>
Score: 0

Could do it pretty easy with jQuery;

$(function() {
    $("#myselectlist option[@value='ItemToSelectValue'].attr('selected', 'true');
});

0

Score: 0

I needed a dropdown in a editable grid myself 10 with preselected dropdown values. Afaik, the 9 selectlist data is provided by the controller 8 to the view, so it is created before the 7 view consumes it. Once the view consumes 6 the SelectList, I hand it over to a custom 5 helper that uses the standard DropDownList 4 helper. So, a fairly light solution imo. Guess 3 it fits in the ASP.Net MVC spirit at the 2 time of writing; when not happy roll your 1 own...

public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
{
    return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
}
Score: 0

I agree with @awrigley and others that it 17 is better to load the selected value using 16 the selectlist constructor in the usual 15 case when you have a single dropdownlist. However, sometimes, one 14 needs to set the selected value on the view, such 13 as when you have a page with n identical 12 dropdowns. Since it is not practical to 11 create such collections in the controller 10 and may not even know in advance how many 9 dropdowns you need, a better approach is 8 to create one instance in the viewmodel 7 as a template with no selected value set 6 and then dynamically create the rest dynamically 5 on the view.

I run into this often when 4 iterating through a list of child items 3 on edit views when the children need dropdowns. In 2 such cases, you can do it like this with 1 one line of code:

@Html.DropDownListFor(x => myViewModelFieldName, new SelectList(Model.MyRawSelectListFromMyViewModel.Select(x=> new {x.Value, x.Text}), "Value", "Text", TheValueYouWantToSelect))

More Related questions