【问题标题】:Creating a html helper for an object为对象创建 html 助手
【发布时间】:2018-06-22 12:41:53
【问题描述】:

嗨,我真的被这个难住了,然后它又是我的第一个 html 助手之一(我没有捏过)。

基本上我有一个对象和几个选项,然后我想显示一个带有几个选项的标签。

到目前为止我的代码是

public static IHtmlString DocumentModalLink(this HtmlHelper htmlHelper, CesaDocument  doc, string title, string model, string style, string inner)
        {
            var builder = new TagBuilder("a");

            builder.MergeAttribute("title", title);
            builder.MergeAttribute("href", "javascript:;");
            builder.MergeAttribute("data-toggle", "model");
            builder.MergeAttribute("data-target", model);
            builder.AddCssClass("btn");
            builder.AddCssClass("btn-" + style);

            builder.InnerHtml = inner;

            builder.MergeAttribute("data-docid", doc.Id.ToString());
            builder.MergeAttribute("data-docdate", htmlHelper.DisplayFor(x => doc.DocDate).ToString());
            builder.MergeAttribute("data-client", htmlHelper.DisplayFor(x => doc.Surname).ToString() + ", " + htmlHelper.DisplayFor(x =>  doc.Forename).ToString());
            builder.MergeAttribute("data-lastmoddate", htmlHelper.DisplayFor(x => doc.Modified).ToString());
            builder.MergeAttribute("data-lastmoduser", htmlHelper.DisplayFor(x => doc.ModifiedBy.Value).ToString());
            builder.MergeAttribute("data-docname", htmlHelper.DisplayFor(x => doc.Name).ToString());
            builder.MergeAttribute("data-docsection", htmlHelper.DisplayFor(x => doc.SectionLookup.Value).ToString());
            builder.MergeAttribute("data-businessunit", htmlHelper.DisplayFor(x =>  doc.BusinessUnitLookup.Value).ToString());
            builder.MergeAttribute("data-doctitle", htmlHelper.DisplayFor(x =>  doc.DocTitle.Value).ToString());


            return MvcHtmlString.Create(builder.ToString());




        }

我可以使用 @Html.DocumentModalLink(d, "Notification", "#NotificationsCreateModal","primary", "<span class=\"glyphicon glyphicon-bell\"></span>") 调用它

但这不起作用。 DisplayFor 仅适用于我不知道如何成功使用的表达式。

我真正的问题是我想要正确格式化的 docDate。 所以基本上是的,如何在多个字段的帮助器中使用 DisplayFor。

谢谢

【问题讨论】:

  • 您可以使用Display() 代替DisplayFor()。或者,更改扩展方法以接受表达式。但是为此创建一个扩展方法是多余的(它只接受一个特定的模型,而不是扩展方法的用途)所以你应该为你的模型创建一个DisplayTemplate
  • DisplayTemplate - 你的意思是部分视图?如果是这种情况,那么向它们添加参数的最佳方法是什么?目前除了使用 viewBag 似乎没有什么好方法。我似乎无法掌握何时使用哪个。

标签: c# razor html-helper


【解决方案1】:

您为什么使用DisplayFor(x => doc.DocDate)?如果该类型存在,则使用 HTML 或其他显示模板呈现该值。

您只想将值呈现为属性。使用 doc.DocDate 等等,就像使用 doc.Id 一样

【讨论】:

  • 因为我想获得正确的日期格式 - 即我在对象中指定的格式。问题是它不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多