views:

3553

answers:

7

Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created? Isn't that a bit silly?

A: 

You mean client-side, in the browser?

var select = document.getElementById('mySelect');
select.options[newIndex].selected = true;
Tor Haugen
+2  A: 

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

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

GalacticCowboy
Why, for the love of god, is it readonly?And why can't you manipulate the items after instantiation?And why then can it not be exposed as a readonly array? This datatype goes beyond me!
borisCallens
If you don't like it, write your own version. Its not that complicated, guy.
Will
@ will: True, but I don't think I'm the only one with these feelings towards the SelectList class. SHould we all write our own then?
borisCallens
A: 

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

ViewData["StateCode"] = "VT";

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

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

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

Ben Mills
I noticed that it starts making sence when you use a regular collection in controller and selectlist only at the very last moment in view. Although I don't really like it that way, it does take away a lot of the friction...
borisCallens
A: 

The SelectList object is readonly after it was created. if you want to select something 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>
linh1987
I try to stay away from the code behind because this would distribute code between my controller, my view AND my code behind.What I do now is instantiate the SelectListItem in the view. Not how I prefer it, but that's just how the cookie crumbles.
borisCallens
A: 

Could do it pretty easy with jQuery;

$(function() {
    $("#myselectlist option[@value='ItemToSelectValue'].attr('selected', 'true');
});
CmdrTallen
The question is actually talking about the C# type SelectList. I'll update the OP to remove the confusion.
borisCallens
A: 

I needed a dropdown in a editable grid myself with preselected dropdown values. Afaik, the selectlist data is provided by the controller to the view, so it is created before the view consumes it. Once the view consumes the SelectList, I hand it over to a custom helper that uses the standard DropDownList helper. So, a fairly light solution imo. Guess it fits in the ASP.Net MVC spirit at the time of writing; when not happy roll your 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));
}
Erik Lenaerts
+1  A: 

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

Thinking this way, a SelectList is a type to feed the dropdownlist html helper. It is NOT a place to store data while you decide how to process it.

A better solution would be to retrieve your data into a List and then only initialise the SelectList(s) when you need to. An immediate benefit of this praxis is that it allows you to reuse your List for more than one dropdownlists, such as:

Country of birth Country of residence...

These SelectLists all use the Countries list of type List.

You can use your List at the 'last minute' like 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 should keep your data in a List till you really need to spit it out. Ie, the last possible minute (LPM).

Andrew

awrigley
This is indeed the way I went. In my view I then create a SelectList from my list. Where applicable, I have a helper method that does this.
borisCallens