自定义HtmlHelper方法,生成<input type =“range”/> HtmlString

时间:2013-01-16 04:18:01

标签: c# asp.net-mvc html5 lambda

据我所知,HtmlHelper类中没有(扩展)方法可以生成类型为input的HTML5 range元素,因此我尝试实现自己的扩展HtmlHelper类:

public static class MvcHtmlHelper
{
    public static HtmlString RangeFor<TModel, TProperty>
    (this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes)
    {
        var name = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression,
                       htmlHelper.ViewData);
        //var min = (string)((ViewDataDictionary<TModel>)htmlAttributes)["min"];
        //var max = (string)((ViewDataDictionary<TModel>)htmlAttributes)["max"];
        //var value = (string)((ViewDataDictionary<TModel>)htmlAttributes)["value"];
        return Range(htmlHelper, min, max, value);
    }

    public static HtmlString Range(this HtmlHelper htmlHelper, 
        string name, string min, string max, string value = "0")
    {
        var builder = new TagBuilder("input");
        builder.Attributes["type"] = "range";
        builder.Attributes["name"] = name;
        builder.Attributes["min"] = min;
        builder.Attributes["max"] = max;
        builder.Attributes["value"] = value;
        return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));
    }
}

我正在尝试模拟现有的TextBoxFor扩展方法,该方法允许调用者通过匿名对象指定额外的htmlAttributes。但是我在上面的注释行上得到InvalidCastException

有人能指出我从匿名htmlAttributes对象获取值的正确方法(类似于TextBoxFor处理htmlAttributes的方式吗?

1 个答案:

答案 0 :(得分:2)

InputExtensions.TextBoxFor以下列方式处理属性:

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
  return InputExtensions.TextBoxFor<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

所以你必须在使用之前从不对称的对象创建属性字典