2016-03-25 119 views
-1

我正在用ASP.NET MVC和Bootstrap構建應用程序。在我的應用程序,我有一個模型,它看起來像這樣一個觀點:ASP.NET MVC - 在自定義HTML助手中使用模型

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

我想從性能輔助生成labelValuecontrolIdpropertyValue值的模型。例如,我想使用@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幫手。

+0

瞭解使得強類型heplers [這裏](http://www.codeproject.com/Tips/389747/Custom-Strongly-typed-HtmlHelpers-in-ASP-NET-MVC) –

+0

@KartikeyaKhosla - 但我怎麼從屬性上的數據屬性? –

回答

0

使用這個例子作爲參考:

 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)