Override Html.DropDownListFor()



我在Mysql中有一个定义表。它很容易,为。例

GroupId Name
1       Colors
2       Size
DefinitionId GroupId Name
1            1       Black
2            1       Green
3            2       S
4            2       M

我使用DropdownListFor。我想创建自定义控件,如下拉列表。例如:

Html.CustomDropDownList("sizeId", 2( <--- 2 是 Group of size。

我怎样才能创建这样的控件。

最后是返回拥有这样的东西。

<select Id="sizeId" name="sizeId">
  <option value="3">M</option>
  <option value="4">S</option>
</selec>

其实就是这么简单。

//This overload is extension method accepts name, list and htmlAttributes as parameters.
    public static MvcHtmlString DefinitionFor(this HtmlHelper helper, string name, int GroupId, object htmlAttributes)
    {
        // ref to db
        var db = (Service.Interfaces.ISet<Definition>)
        DependencyResolver.Current.GetService(typeof(Interfaces.ISet<Definition>));
        //Creating a select element using TagBuilder class which will create a dropdown.
        TagBuilder dropdown = new TagBuilder("select");
        //Setting the name and id attribute with name parameter passed to this method.
        dropdown.Attributes.Add("Key", name);
        dropdown.Attributes.Add("Id", name);
        //Created StringBuilder object to store option data fetched oen by one from list.
        StringBuilder options = new StringBuilder();
        //Get Item(s)
        var items = db.Get(new Definition() { Group = new Group() { Id = GroupId } }).List;
        foreach (var item in items)
        {
            //Each option represents a value in dropdown. For each element in the list, option element is created and appended to the stringBuilder object.
            options = options.Append("<option value='" + item.Id + "'>" + item.Key + "</option>");
        }
        //assigned all the options to the dropdown using innerHTML property.
        dropdown.InnerHtml = options.ToString();
        //Assigning the attributes passed as a htmlAttributes object.
        dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        //Returning the entire select or dropdown control in HTMLString format.
        return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
    }

然后,我可以这样打电话。

<div>
    @Html.DefinitionFor("colorId", 2, new { @class = "form-control" });
</div>

祝您编码愉快!

相关内容

  • 没有找到相关文章

最新更新