9

I am facing a simular problem as outlined in the question "Html.DropDownList in ASP.NET MVC RC (refresh) not pre-selecting item"

I'm using ASP.net MVC 1.0 and need to associated a javascript call when the DropDownList is changed.

<%=Html.DropDownList("SelectList", 
                    (SelectList)ViewData["SelectList"], 
                     new { onchange="javascript:selected_droplist();" } )%>

This is all good except it is ignoring my pre-selected item

If I remove the extra functionality:

<%=Html.DropDownList("SelectList")%>

It is happy and will use my pre-selected item. BUT i don't get the Javascript action!

So, how do i add the javascript to the onchange event?

Community
  • 1
  • 1
Andrew Harry
  • 13,773
  • 18
  • 67
  • 102

3 Answers3

20

Found the Answer

When the Name given to the control (the first parameter in this case being "SelectList") is the same as one of the Keys in the ViewData dictionary basically it screws up and ignores the pre-selected item in the SelectList

By simply renaming the DropDownList it works correctly and binds to the Pre-Selected item

Community
  • 1
  • 1
Andrew Harry
  • 13,773
  • 18
  • 67
  • 102
0

I know this is an old post, but I found a link that shows a workaround where you can keep the same name for the dropdown list and keep data binding for the model on the form post:

http://publicityson.blogspot.com/2010/07/aspnet-mvc-htmldropdownlist-not-showing.html

I think this is a huge bug and am surprised it's not been fixed yet. Anyways, I hope this helps.

Tom Schreck
  • 5,177
  • 12
  • 68
  • 122
0

Unfortunately i'm not at work so i can't get the actual code. However, I accomplished this by writing the javascript event as an html attribute in the Controller, then passed it along in the ViewData.

When you write the code:

<%=Html.DropDownList("SelectList", (SelectList)ViewData["SelectList"], [htmlAttribute])

Basically in the Controller you would write the htmlattribute and assign it in the dropdownlist method.

Jack Marchetti
  • 15,536
  • 14
  • 81
  • 117
  • Thanks for answering, but if you read my full question you will see that i can get this to work like you have just said, BUT it doesn't use my pre-selected item – Andrew Harry Jun 11 '09 at 03:08