扩展MVC RadioButtonFor使用HtmlHelper扩展

时间:2015-11-11 01:03:56

标签: model-view-controller custom-controls

我正在尝试构建一个HtmlHelper来为MVC RadioButtonFor控件添加功能。我只想在给定条件的情况下向单选按钮添加类和样式属性。我似乎无法获得包含属性的扩展。我已经按照我在网上找到的几个例子,但没有运气。

这是我的代码:

public static MvcHtmlString GCSRadioButtonForHelper<TModel>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, bool?>> expression,
        Object htmlAttributes,
        object value            )
    {

        bool isRequired = false;
        bool isHidden = false;
        object styleList;
        object classList;

        Dictionary<string, object> attributes = new Dictionary<string, object>();
        attributes.TryGetValue("class", out classList);
        attributes.TryGetValue("style", out styleList);

        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        var categoryName = string.Empty;
        if (metadata.ContainerType != null)
            categoryName = metadata.ContainerType.Name + "." + metadata.PropertyName;

        isHidden = GetIsHidden(metadata);
        isRequired = GetIsRequired(metadata);

        if (isHidden)
            classList = classList + " GCSHidden ";

        if (isRequired)
        {
            classList = classList + " GCSRequired ";
        }

        attributes.Remove("class");
        attributes.Remove("style");

        attributes.Add("class", classList);
        attributes.Add("style", styleList);

        //Render HTML String
        MvcHtmlString html = System.Web.Mvc.Html.InputExtensions.RadioButtonFor(htmlHelper, expression, attributes, value);
        return html;

    }

问题是InputExtensions.RadioButtonFor()的结果从不包含我指定的属性类或样式。有任何想法吗?

TIA

0 个答案:

没有答案