据我所知,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
?