Selected value not working for SelectList
Asked Answered
E

2

18

I found many questions and answers related to this issue but nothing worked for me

I am creating a dropdown list like this

@Html.DropDownListFor(m => m.SchoolYears, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })

(Model.CurrentYearId is of type int)

But it never lets current year selected.

From this post, I got that we should use string for selected value (although I don't know why because it allows object for selected value)

DropDownList SelectList SelectedValue issue

so I tried all these variations

new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId.ToString())

new SelectList(Model.SchoolYears, "YearId", "StartDates", 2)

new SelectList(Model.SchoolYears, "YearId", "StartDates", "2")

But they even didn't work.

There is way to create the select list through linq query or foreach loop and mark selected property of each item but why the above doesn't work?

Execute answered 17/5, 2013 at 8:6 Comment(0)
E
24

Found the problem.

The mistake I was doing is using this

m => m.SchoolYears // m.SchoolYears in a list of string

When I changed it to this

m => m.SelectedYearId // m.SelectedYearId is an integer property

it worked like a charm, so finally I have this working

@Html.DropDownListFor(m => m.SelectedYearId, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })

Thanks!

Execute answered 17/5, 2013 at 8:16 Comment(2)
What do I do if I need a string ID?Hagood
I'm using MVC5 but still got the same problemRorie
A
12

The solution did not work for me. It turns out selected property doesnot work if the ViewBag Property name and Model Property name is same so after changing the ViewBag Property name it worked.

Alleluia answered 8/10, 2017 at 19:41 Comment(1)
This was the case with me too. And is important to note: it's not case sensitive. ViewBag.myvariablename will affect to @Html.DropDownListFor(m => m.MyVariableName, ...) as well.Avidin

© 2022 - 2024 — McMap. All rights reserved.