Set selected value in SelectList after instantiation

后端 未结 10 2021
长发绾君心
长发绾君心 2020-12-05 17:39

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?

相关标签:
10条回答
  • 2020-12-05 18:20

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

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

    This works well on an edit page, but not for Create when you want to preselect a specific value, so one workaround is simply to assign the correct value on a default constructed object you pass to the view 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 View that looks like this:

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

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

    0 讨论(0)
  • 2020-12-05 18:21

    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>
    
    0 讨论(0)
  • 2020-12-05 18:21

    Could do it pretty easy with jQuery;

    $(function() {
        $("#myselectlist option[@value='ItemToSelectValue'].attr('selected', 'true');
    });
    
    0 讨论(0)
  • 2020-12-05 18:23

    I think you are fighting the framework. The data going 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<T> and then initialize the SelectList(s) when you need to. An immediate benefit of this practice is that it allows you to reuse your List<T> for more than one DropDownList, such as:

    Country of birth
    Country of residence
    

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

    You can use your List<T> 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<T> till you really need to output it; the last possible minute (LPM).

    0 讨论(0)
提交回复
热议问题