【发布时间】:2012-11-23 22:50:09
【问题描述】:
我创建了一个简单的方法来扩展 HtmlHelper.. 基本上它是 TextBoxFor 方法,但经过定制以更好地适应我的目的.. 无论如何.. 我认为 HtmlHelper 使用新 { @attributename = " 的方式attributevalue" } thingy 创建 html 元素属性真的很整洁.. 所以我的问题是.. 我怎么能做同样的事情?
查看代码:
@Html.DaisyTextBoxFor(model => model.Text, new { @class="asd" })
帮助代码:
public static MvcHtmlString DaisyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string,object> attributes = null)
{
var value = ((PropertyViewModelProperty)htmlHelper.ViewData.Model.GetType().GetProperty(ExpressionHelper.GetExpressionText(expression)).GetValue(htmlHelper.ViewData.Model, null)).Value;
return MvcHtmlString.Create(String.Format("<input name=\"{0}\" value=\"{1}\" />", CreateForInputName(typeof(TModel), htmlHelper), value));
}
private static string CreateForInputName(Type model,HtmlHelper htmlHelper)
{
return HttpContext.Current.Server.HtmlEncode(model.AssemblyQualifiedName + "_" + htmlHelper.ViewData["propertyName"].ToString() + '_' + htmlHelper.ViewData["propertyGuid"].ToString());
}
【问题讨论】:
-
RouteValueDictionary有一个以object为参数的构造函数。将其与匿名对象一起使用。这可以与 p.e. 一起使用。TagBuilder的MergeAttributes -
能否给我一个代码示例,我不太明白我应该如何使用 RouteValueDictionary 作为该方法的参数..
-
现在我明白了 :),谢谢!
标签: c# asp.net-mvc attributes html-helper