Search code examples
asp.net-mvc-4webgrid

MVC4 .Net How to place DropDown in WebGrid Cell


I have seen a number of questions that are similar to this one, but I have not come across one with an answer that works for me. Yet :)

My Model looks like this:

public class MyModel
{
    public List<MyItem> MyItems{get;set;}
    public List<SelectListItem> MySet{get;set;}
}

MyItem looks like this:

public class MyItem
{
    public int MyItemId
}

My view has @model MyModel at the top.

My WebGrid looks like this:

@{
    var grid = new WebGrid( Model.MyItems, canPage: false );
        var gridColumns = new List<WebGridColumn>
        {
            grid.Column( 
                format: (item) => @Html.DropDownListFor(modelItem => item.MyItemId.ToString(), Model.MySet ) )
        };
        @grid.GetHtml( "wgtable",
            rowStyle: "gridrow",
            alternatingRowStyle: "altgridrow",
            displayHeader: true,
            columns: grid.Columns( gridColumns.ToArray( ) ) )
    }

In this case, the error I get is CS1963: An expression tree may not contain a dynamic operation.

I have also tried

format: (item) => @Html.DropDownListFor(item.MyItemId.ToString(), Model.SubPayGroups ) )

which gives me CS1973: Model has no applicable method named 'DropDownListFor'.

Am I even close?


Solution

  • I ended up moving away from DropDownListFor, using DropDownList instead, also building an IEnumerable: this was my final working solution for the column:

        grid.Column(
            header:"Sub Pay Group",
            format: (item) => @Html.DropDownList("MyItemId", Model.MySet.Select( u => new SelectListItem
            {
                Text = u.Text,
                Value = u.Value,
                Selected = u.Value == ((WebGridRow)item)["SubPayGroupId"].ToString() }),
    

    It wasn't in my initial problem definition, but I also needed to set a selected item. Thus, the additional Select from MySet...