Set selected value in SelectList after instantiation

后端 未结 10 2066
长发绾君心
长发绾君心 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.

提交回复
热议问题