I have been creating a project that uses the
ASP.NET MVC Framework.
I am using a select dropdown for the user to be able to select a "Faculty" which is a child object of a "Course". I'm going to use the
Html.Select() extension method to do this. So my code goes like this:
<%= Html.Select("Faculty", FacultyData, "Title", "Id") %>
No problem here, I get my list of Faculties, nice and easy.
Right, because I'm know creating the edit page I want this dropdown to have the correct Facility selected when the page loads i.e have a selected value set.
The
Html.Select takes a fifth property of type
object. The inner workings of the
MVC Framework compares this object with the value of the option that is currently being rendered as to whether or not to place a "selected" attribute.
So my code now reads:
<%= Html.Select("Faculty", FacultyData, "Title", "Id", ViewData.Faculty.Id.ToString()) %>
Because the value on the select option is of type
string, I have to convert my Id (which is of type
Guid) to a
string so that I don't get a cast exception .
However the above code does not work because the
Html.Select method also takes type of
IEnumerable and a
string is an Enumerable of
Char. This is a problem because when the
MVC Framework gets the
Enumerator for the
string it returns an
CharEnumerator and tries to compare the first letter in my Id with the
string value. This throws a cast exception as it can't compare type
char to type
string.
In order to get round this problem I have had to explicitly set the Id to be of type
object like so:
<%= Html.Select("Faculty", FacultyData, "Title", "Id", (object)ViewData.Faculty.Id.ToString()) %>
Now the framework will create an
IEnumerable of objects and then everything works fine. Bit of a pain and took a lot of debugging to get to the bottom of it. Just remember the a
string object is of type
IEnumerable.