R – asp mvc DropDownList how to pass a selected item in visual basic .net

asp.net-mvcdrop-down-menu

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

Best Answer

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)) %>