asp.net-mvcasp.net-mvc-2

Getting problem while displaying Dropdown list box values in asp,net mvc application


I am getting following error when I am passing the Dropdown list box values..

DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'code'.

Here is my dropdown list box code in my view.

<span id="StateFilterRow"> State: <%= Html.DropDownList("StatesFilter", new SelectList(Model.StatesList, "code", "code", Model.SelectedState), new { style = "background-color: #eee; font-weight:bold;" })%></span>  

Here is my code to get the Dropdown list box values.

In my result States I have text and value for States

  Text  = '{code = AL}'

In my ViewModel..

  public SelectList StatesList { get; set; }

Is that something I am doing wrong in my view code?


Solution

  • Your getListOfStates method already returns a SelectList, so in your view you don't need to create yet another one. So you could modify this method and specify the properties there:

    private SelectList getListOfStates()
    {
        var values = 
            from s in generic.CodeTypes
            join c in generic.ApplicationCodes on s.CodeType_Id equals c.CodeType_ID
            where s.CodeType_Id == 26
            select new
            {
                Code = c.Code,
            };
        return new SelectList(values, "Code", "Code");
    }
    

    and then in your view:

    <%= Html.DropDownList(
        "StatesFilter", 
        Model.StatesList, 
        new { style = "background-color: #eee; font-weight:bold;" }
    ) %>