views:

109

answers:

1

I am new to MVC, so sorry if I am being a bit thick. I am using VB

I am trying to fill an html drop down list using data from a db, but the first item is always selected, no matter what.

What am I doing wrong?

Here is my code - In the controller:

ViewData("MatchTypeList") = New SelectList(_db.GetMatchTypes.ToList(), "MatchTypeID", "MatchTypeName", SelectedValue)

And in the view

<%= Html.DropDownList("MatchType", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>
A: 

This is a problem with mvc. One work around would be to change the name of the dropdownlist to anything but the name of the property. Then, before submitting to change the name back to the true name of the property.

An example:

<script type="text/javascript">

    $(function () {
        $("form").submit(function () {
            $("select").each(
                function () {
                   $(this).attr("name", $(this).attr("name").replace(/ZZZ/, ''));
            });
        });
    });

</script>

<%= Html.DropDownList("MatchTypeZZZ", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>

I place the javascript (it uses JQuery) in my master page so any form in the app that has a dropdownlist can safely have its name appended with ZZZ and then set back to its original name on submission.

ondesertverge