hersh
hersh

Reputation: 1183

creating dropdownlist from ViewData

Does anyone have any idea why the code below doesn't give me any value but instead gives me "System.Web.Mvc.SelectListItem"?

If I don't do a foreach but instead substitute the ViewData with this

<%= Html.DropDownList("PersonOnCallCheckBoxList") %>, I get the correct value. Please help.

foreach (var person in ViewData["Person"] as IEnumerable)
{
%>
   <input type="checkbox" value="<%= person %>" /><%= person %><br />
<%
}

Upvotes: 0

Views: 180

Answers (2)

hersh
hersh

Reputation: 1183

          <%
            var list = this.ViewData["Persons"] as SelectList;

            foreach (var person in list)
            {
              %>
                  <input id="cbPerson" type="checkbox" value="<%= person.Value %>" />
                  <label for="cbPersonOnCall"><%= person.Text %></label><br />
              <%
            }
          %>

Upvotes: 0

anq
anq

Reputation: 3262

Because person is a SelectListItem.

use person.Text to get the displayed text and person.Value to get the backing value

Html.DropDownList is built for working with SelectListItems so it does the right thing, but if you are manually working with the Items you'll have to get the Value and Text yourself.

Upvotes: 3

Related Questions