ASP.NET MVC,CheckBoxFor()属性问题

时间:2015-09-08 09:33:46

标签: asp.net-mvc

当我像这样使用CheckBoxFor()HtmlHelper时:

@Html.CheckBoxFor(x => Model.IsDeleted, new { myCustomAttribute = "myCustomAttribute" })

我的复选框有属性,但隐藏的元素没有。

<input myCustomAttribute="myCustomAttribute" id="IsDeleted" name="IsDeleted" type="checkbox" value="true">
<input name="IsDeleted" type="hidden" value="false">

如何将属性添加到隐藏元素?我不想写自定义HTML。

1 个答案:

答案 0 :(得分:0)

在我看来,实现此类功能的最简单方法是创建自定义助手:)来自http://20fingers2brains.blogspot.com/2013/05/custom-checkbox-html-helper-in-mvc3.html的简单助手:

public static class CustomCheckBoxHelper
{
    //This helper accepts name attribute. This method in turns calls our second overload.
    public static MvcHtmlString Custom_Checkbox(this HtmlHelper helper, string name)
    {
        return Custom_Checkbox(helper, name, false);
    }

    //This helper accepts name and isChecked boolean attribute. 
    public static MvcHtmlString Custom_Checkbox(this HtmlHelper helper, string name,bool isChecked)
    {
        return Custom_Checkbox(helper, name, isChecked, null);
    }

    //This overload accepts name, isChecked and htmlAttributes as parameter.
    public static MvcHtmlString Custom_Checkbox(this HtmlHelper helper, string name,bool isChecked,object htmlAttributes)
    {
        //Creating input control using TagBuilder class.
        TagBuilder checkbox = new TagBuilder("input");

        //Setting its type attribute to checkbox to render checkbox control.
        checkbox.Attributes.Add("type", "checkbox");

        //Setting the name and id attribute.
        checkbox.Attributes.Add("name", name);
        checkbox.Attributes.Add("id", name);

        //Adding the checked attibute based on parameter received.
        if (isChecked)
            checkbox.Attributes.Add("checked", "checked");

        //Merging the other attributes passed in the attribute.
        checkbox.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        return MvcHtmlString.Create(checkbox.ToString(TagRenderMode.Normal)); 
    }
}