Consuming a Helper code for optgroup functionality in Asp.net MVC

不羁的心 提交于 2019-11-29 10:31:03

We use Serge Zab's helper for optgroup dropdowns. Here is a sample:

The viewmodel:

public class OurViewModel
{
    public int? TypeId { get; set; }
    public IEnumerable<GroupedSelectListItem> GroupedTypeOptions { get; set; }
}

The controller:

public ActionResult Add()
{
    var model = new OurViewModel
    {
        // fill with initial values
    };
    PutTypeDropDownInto(model);
    return View(model);
}

[NonAction]
private void PutTypeDropDownInto(OurViewModel model)
{
    model.GroupedTypeOptions = _repos.GetTypes()
        .OrderBy(t => t.Category.EnglishName).ThenBy(t => t.EnglishName)
        .Select(t => new GroupedSelectListItem
        {
            GroupKey = t.Category.RevisionId.ToString(),
            GroupName = t.Category.EnglishName,
            Text = t.EnglishName,
            Value = t.RevisionId.ToString()
        }
    );
}

The view

@Html.DropDownGroupListFor(m => m.TypeId, Model.GroupedTypeOptions, 
    "[Select a type]")

Note that you can't use a regular SelectList. You have to use a collection of his GroupedSelectListItem class. Also, our solution doesn't use viewbag. The dropdown list is strongly typed on the viewmodel.

Update

To get the html helper to work in your view, the view needs to be able to find it. You can either add a @using directive at the top of the view with your MyExtensionClass.cs namespace, or add the namespace to the view-specific web.config, like so:

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="Microsoft.Web.Mvc" />
    <add namespace="Namespace.For.MyExtensionClass" />
  </namespaces>
</pages>

This was added to ASP.NET MVC at version 5.2!

Property Group in SelectListItem allows you to specify a group for each item

Html.DropDownList() and DropDownListFor() now generate optgroup elements based on the groups included on the list of items.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!