1

据我所知,HtmlHelper类中没有(扩展)方法可以生成 HTML5input类型的元素,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

4

1 回答 1

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));
}

所以你必须在使用它之前从异常对象创建属性字典

于 2013-01-16T06:42:38.893 回答