mvcgrid.net

What's the best way to implement an inline DropDownList using MVCGrid.net?


I'm using MVCGrid.net (http://mvcgrid.net). I have a grid of Items. Say the view model for my Item looks like this:

public class ItemViewModel
{
    public string ItemNumber { get; set; }
    public string ItemStateId { get; set; }
}

I'd like to be able to change the item state from within the grid using a drop down list. I think I have a good solution for this using the API that is available. I just want to make sure this is the best approach. My intention is to render the drop down list using the code below. Then have a jquery event handler on the "change" event for "ItemStateSelector" to handle actually changing the status of the item with an ajax request. Aside from the performance issue of retrieving the available states for each item in the query result, is this the best solution to the problem?

public static void RegisterGrids()
{
    MVCGridDefinitionTable.Add("ItemsGrid", new MVCGridBuilder<ItemViewModel>()
        .WithAuthorizationType(AuthorizationType.AllowAnonymous)
        .AddColumns(cols =>
        {
            cols.Add("ItemNumber")
                .WithHeaderText("Item #")
                .WithValueExpression(p => p.ItemNumber);
            cols.Add("ItemStateId")
                .WithHeaderText("Status")
                .WithValueExpression(p => GetItemStatusValueExpression(p.ItemStateId))
                .WithValueTemplate("{Value}", false);
        })
        .WithRetrieveDataMethod(context =>
        {
            var options = context.QueryOptions;
            int totalRecords;
            var items = SearchManager.SearchItems(out totalRecords, options);

            return new QueryResult<ItemViewModel>
            {
                Items = items.ToList(),
                TotalRecords = totalRecords
            };
        })
    );
}

private static string GetItemStatusValueExpression(int itemStateId)
{
    var states = ItemManager.GetItemStates();
    var builder = new StringBuilder();
    builder.Append("<select class='form-control ItemStateSelector'>");

    foreach (var state in states)
    {
        builder.Append(state.ItemStateId == itemStateId
            ? String.Format(CultureInfo.InvariantCulture, "<option value='{0}' selected='selected'>{1}</option>",
                state.ItemStateId, state.ItemStateName)
            : String.Format(CultureInfo.InvariantCulture, "<option value='{0}'>{1}</option>", state.ItemStateId,
                state.ItemStateName));
    }

    builder.Append("</select>");

    return builder.ToString();
}

Solution

  • I took a look at how you implemented it, and reproduced it locally. I can say that at this time, this is the best way to do it. If you have any thoughts on how it could be made easier, I would love to hear them!