Dropdownlist selected value in asp.net mvc

Total Post:154

Points:1086
 1512  View(s)
Ratings:
Rate this:
 have tried this is RC1 and then upgraded to RC2 which did not resolve the issue.
// in my controller
        ViewData["UserId"] = new SelectList(
        users,
        "UserId",
        "DisplayName",
        selectedUserId.Value); // this has a value

result: the SelectedValue property is set on the object.

// in my view
        <%=Html.DropDownList("UserId", (SelectList)ViewData["UserId"])%>

result: all expected options are rendered to the client, but the selected attribute is not set. The item in SelectedValue exists within the list, but the first item in the list is always defaulted to selected.

  1. Post:194

    Points:1396
    Re: ZDropdownlist selected value in asp.net mvc

    Try this:

    public class Person
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

    And then:

    var list = new[] {   
                new Person { Id = 1, Name = "Name1" },
                new Person { Id = 2, Name = "Name2" },
                new Person { Id = 3, Name = "Name3" }
            };
     
            var selectList = new SelectList(list, "Id", "Name", 2);
            ViewData["People"] = selectList;
     
            Html.DropDownList("PeopleClass", (SelectList)ViewData["People"])

    With MVC RC2, I get.

    <select id="PeopleClass" name="PeopleClass">
        <option value="1">Name1</option>
        <option selected="selected" value="2">Name2</option>
        <option value="3">Name3</option>
    </select>

      Modified On Apr-05-2018 07:15:30 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!