首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP.NET MVC -自定义Helper中的使用模型

ASP.NET MVC -自定义Helper中的使用模型
EN

Stack Overflow用户
提问于 2016-03-25 14:16:37
回答 1查看 3.4K关注 0票数 0

我正在构建一个应用程序与ASP.NET MVC和引导。在我的应用程序中,我看到的模型如下所示:

代码语言:javascript
复制
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助手,如下所示:

代码语言:javascript
复制
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视图中使用这个助手和模型,如下所示:

代码语言:javascript
复制
@model EntryModel
<h2>Hello</h2>

@using (Html.BeginForm("Add", "Entry", new {}, FormMethod.Post, new { role="form" }))
{
  @Html.MyTextBox() 
}

我试图从模型的属性中生成助手中的labelValuecontrolIdpropertyValue值。例如,我希望使用@Html.MyTextBoxFor(m => m.Name)并让助手生成如下内容:

代码语言:javascript
复制
<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助手中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-25 18:23:35

使用此示例作为参考:

代码语言:javascript
复制
        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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36221656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档