views:

420

answers:

2

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.Gender 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...

A: 

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

Si Gardner
Good thought. Turns out donor.Gender is a char in the database. However, trying this: ViewData["Gender"] = new SelectList(new[] { "Female", "Male", "Unknown" }, donor.Gender.ToString());still brings no joy. Now, this could be because the Model.Gender is still a char--not sure what to do about that.
dale
you could always create another property on the Gender object and have that return the correct string based on the value of the char
Si Gardner
sorry i meant donor
Si Gardner
Thanks Si for getting me on the right track. The solution I've come up with follows below, but basically I make sure that donor.Gender is padright(int) where int is the length of the DB chararray. The other trick was to include the appropriate white space in the static SelectList values. With the, MVC Html.DropDownList() works its magic flawlessly. Lesson: don't assume anything about db types :-)
dale
A: 

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.

dale