繁体   English   中英

html元素属性,自定义HtmlHelper.xxxxFor

[英]html-element attributes, custom HtmlHelper.xxxxFor

我创建了一个简单的方法,扩展了HtmlHelper ..基本上是它的TextBoxFor方法,但是为了更好地适应我的目的,做了一点定制。.无论如何..我认为HtmlHelper使用新的{@attributename =“ attributevalue”}的方式创建html-element属性真的很整洁..所以我的问题是..我将如何做同样的事情?

ViewCode:

@Html.DaisyTextBoxFor(model => model.Text, new { @class="asd" })

HelperCode:

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

我从来没有尝试过,但是下面的东西行不通吗?

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}部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM