【问题标题】:html-element attributes, custom HtmlHelper.xxxxForhtml-element属性,自定义HtmlHelper.xxxxFor
【发布时间】: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. 一起使用。 TagBuilderMergeAttributes
  • 能否给我一个代码示例,我不太明白我应该如何使用 RouteValueDictionary 作为该方法的参数..
  • 现在我明白了 :),谢谢!

标签: c# asp.net-mvc attributes html-helper


【解决方案1】:

我从来没有尝试过,但是下面的东西不起作用吗?

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}\" class=\"{2}\" />", CreateForInputName(typeof(TModel), htmlHelper), value, attributes["class"]));
    }

注意MvcHtmlString.Create 部分中的class={2} 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 2011-07-19
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多