【发布时间】:2014-07-09 16:06:30
【问题描述】:
我正在尝试制作一个自定义 HtmlHelper,它将在现有 HtmlHelper 的帮助下生成多个 HTML 元素,例如 Html.TextBoxFor 和 Html.LabelFor。我遇到的主要问题是我无法创建这些现有助手使用的表达式,除非它们都单独传递到我的自定义 HtmlHelper 中。我希望能够将整个模型传递给自定义 HtmlHelper 并在帮助器内部创建表达式并将它们传递给现有的。我正在尝试这样做,希望这些属性仍然有效,例如 DisplayName 的必需和国际化。这可能吗?
我知道我可以通过表达式将每个 Address 属性传递给自定义 HtmlHelper 来做到这一点,但它不像在帮助程序中完成那样干净和易于使用。
地址模型
public class Address
{
[Required(ErrorMessage = "Required"), DisplayName("First Name")]
public String FirstName { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("Last Name")]
public String LastName { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("Line 1")]
public String Line1 { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("Line 2")]
public String Line2 { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("City")]
public String City { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("State")]
public String State { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("Country")]
public String Country { get; set; }
[Required(ErrorMessage = "Required"), DisplayName("Postal Code")]
public String PostalCode { get; set; }
}
自定义 HtmlHelper
public static class AddressExtension
{
public static MvcHtmlString AddressEditorForModel<TModel>(this HtmlHelper<TModel> helper, Address address, String prefix, Boolean showLabels)
{
// There will be more markup in here, this is just slimmed down..
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format("<div id='{0}_AddressContainer' >", prefix));
// First Name
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// Last Name
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// Line 1
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// Line 2
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// City
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// State
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// Country
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
// Postal Code
if (showLabels)
sb.AppendLine(helper.DisplayFor(????).ToString());
sb.AppendLine(helper.EditorFor(????).ToString());
sb.AppendLine("</div>");
return MvcHtmlString.Create(sb.ToString());
}
查看(cshtml)
@Html.AddressEditorForModel(Model, "test", true)
【问题讨论】:
标签: c# lambda asp.net-mvc-5 html-helper data-annotations