views:

772

answers:

2

asp mvc DropDownList how to pass a selected item in visual basic .net i put this in the view: <%=Html.DropDownList("Estados", ViewData("EstadosList"))%> and the compiler says that i have to convert to SelectList becouse ViewData Returns an Object any idea to do this?

thxs.. Fernando Soruco

+1  A: 

There are two ways to solve your problem. One is faster, and one is better...

  1. Better version:

    Change your view to a strongly typed one, by changing the Inherits attribute of the Page tag on the top to

    Inherits="System.Web.Mvc.ViewPage<System.Web.UI.WebControls.SelectList>"
    

    (or whatever the full namespace "path" to the SelectList class is...)

    In your Controller action, you send the SelectList to the view as the Model object, by using

    Return View(theSelectListYouCreatedWithItemsFromTheDataStore)
    

    or, if you're returning a view with a different name than the controller action:

    Return View("theViewName", theSameSelectListAsAbove)
    

    In your view, you pass the Model object, now strongly typed to a SelectList because of the View's inheritance, to the helper method:

    <%= Html.SelectList("Estados", ViewData.Model) %>
    
  2. Faster version:

    Cast the ViewData["Estadoslist"] object to a SelectList before you send it to the helper method:

    <%= Html.SelectList("Estados", CCast(ViewData["EstadosList"], SelectList)) %>
    
Tomas Lycken
And if you already send another model to your view, you could wrap them both in a EstadosViewModelWrapper class, which take all the other things you need as properties and gets passed down as the model object instead.
Tomas Lycken
A: 

This is not specifically related to Visual Basic. Please check this article. It describes how to bind MVC dropdownlist: http://www.altafkhatri.com/Technical/How%5Fto%5Fbind%5FIList%5Fwith%5FMVC%5FDropdownlist%5Fbox