Search code examples
asp.net-mvc-4webgrid

WebGrid Dropdownlist error in MVC4


I am trying to develop a WebGrid with dropdownlist, where by default the selected value http://www.mikesdotnetting.com/Article/202/Inline-Editing-With-The-WebGrid

//code in Controller (which grabs more than 1 set of data):

ViewBag.material_codes = new SelectList(db.Master_Material, "material_code", "material_code");

//code in View(WebGrid):

grid.Column("material_code", MenuItemModel.translateMenuItem("MaterialCode"), format: 
                            @<text>
                                 @Html.DropDownList("material_code", (SelectList)ViewBag.material_code, item.material_code)
                            </text>),

However I get the error:

 Error  1   'System.Web.Mvc.HtmlHelper<IMv3.ViewModels.RMReceivingViewModels>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.  

I believe it is caused by "item.material_code", any idea guys?


Solution

  • Extension methods (such as the DropDownList) cannot contain dynamic parameters. So you need to cast the item.material_code to its underlying type:

    @Html.DropDownList(
        "material_code", 
        (SelectList)ViewBag.material_code, 
        (string)item.material_code
    )
    

    Here I cast it to string but if the underlying type is different you should adjust your code.