开发者

MVC 1.0 DropDownList static data select not working

I'm new to MVC and C#. I'm trying to get a static list to work with a DropDownList control such that the selected value rendered is set by the current Model value from the DB.

In the controller, I have:

  ViewData["GenderList"] = new SelectList(new[] { "Female", "Male", "Unknown" }, donor.Gender);  

In the view:

 Gender:<%=Html.DropDownList("Gender", (IEnumerable<SelectListItem>)ViewData["GenderList"]) %>

In the debugger, donor.G开发者_运维技巧ender is "Male", but "Female" gets rendered in the view.

I've read a number of posts related to select, but I've not found one that applies to a static list (e.g., where there's no "value" and "name" to play with). I'm probably doing something stupid...


This may sound like a stupid question but is donor.Gender a string value, and does it match case with the hard-coded values you've used EG 'Male'?

The reason I ask is because this;

ViewData["GenderList"] = new SelectList(new[] { "Female", "Male", "Unknown" }, "Male");

works a treat, but this;

 ViewData["GenderList"] = new SelectList(new[] { "Female", "Male", "Unknown" }, "male");

returns your result


Thanks to Si, here's the final solution I came up with:

In the controller, this:

  ViewData["GenderList"] = repo.GetGenders(donor.Gender);

In the DonorRepository, this:

public SelectList GetGenders(string selected) {
    SelectList genders = new SelectList(new[] { "Female ", "Male   ", "Unknown" }, (selected == null ? null : selected.ToString().PadRight(7).ToCharArray()));
    return (genders);
}

Then in the View, just this:

<%= Html.DropDownList("Gender", (IEnumerable<SelectListItem>)ViewData["GenderList"], "--Select--")%>

NOTE: PadRight(7) equals the Donor.Gender DB specification of Char(7). Also note the SelectList constant space padding of "1234567" for each selectlistitem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜