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 perso开发者_JAVA百科n in ViewData["Person"] as IEnumerable)
{
%>
<input type="checkbox" value="<%= person %>" /><%= person %><br />
<%
}
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.
<%
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 />
<%
}
%>
精彩评论