据我所知,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
的方式吗?
答案 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));
}
所以你必须在使用之前从不对称的对象创建属性字典