我正在构建一个应用程序与ASP.NET MVC和引导。在我的应用程序中,我看到的模型如下所示:
public class EntryModel
{
[Required(ErrorMessage="Please enter the name.")]
[Display(Name="Name")]
public string Name { get; set; }
[Required (ErrorMessage="Please enter the description.")]
[Display(Name = "Description")]
public string Description { get; set; }
}在这个应用程序中,我还定义了一个定制的html助手,如下所示:
public static class MyHelpers
{
public static MvcHtmlString MyTextBox(this HtmlHelper helper)
{
var sb = new StringBuilder();
sb.Append("<div class=\"form-group\">");
sb.Append("<label class=\"control-label\" for=\"[controlId]\">[labelValue]</label>");
sb.Append("<input class=\"form-control\" id=\"[controlId]\" name=\"controlId\" type=\"text\" value=\"[propertyValue]\">");
sb.Append("</div>");
return MvcHtmlString.Create(sb.ToString());
}
}我在Razor视图中使用这个助手和模型,如下所示:
@model EntryModel
<h2>Hello</h2>
@using (Html.BeginForm("Add", "Entry", new {}, FormMethod.Post, new { role="form" }))
{
@Html.MyTextBox()
}我试图从模型的属性中生成助手中的labelValue、controlId和propertyValue值。例如,我希望使用@Html.MyTextBoxFor(m => m.Name)并让助手生成如下内容:
<div class="form-group">
<label class="control-label" for="Name">Name</label>");
<input class="form-control" id="Name" name="Name" type="text" value="Jon">
</div>本质上,我不知道如何将我的模型信息放到我的html助手中。
发布于 2016-03-25 18:23:35
使用此示例作为参考:
public static MvcHtmlString AutoSizedTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
var attributes = new Dictionary<string, Object>();
var memberAccessExpression = (MemberExpression)expression.Body;
var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);
if (stringLengthAttribs.Length > 0)
{
var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;
if (length > 0)
{
attributes.Add("size", length);
attributes.Add("maxlength", length);
}
}
return helper.TextBoxFor(expression, attributes);
}您可以在视图中这样调用它:@Html.AutoSizedTextBoxFor(x => x.Address2)
https://stackoverflow.com/questions/36221656
复制相似问题