2016-03-25 11 views
-1

私はASP.NET MVCとブートストラップでアプリケーションを構築しています。私のアプリでは、私はこのようになりますモデルとビューがあります。私は「ASP.NET MVC - カスタム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()); 
    } 
} 

:このアプリで

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ヘルパーを定義しましたこのように、私のカミソリビューで、このヘルパーとモデルを使用してメートル:

@model EntryModel 
<h2>Hello</h2> 

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

私はプロパティからヘルパーにlabelValuecontrolId、およびpropertyValue値を生成しようとしていますモデルの

<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ヘルパーに私のモデル情報を取得するかどうかはわかりません:たとえば、私は@Html.MyTextBoxFor(m => m.Name)を使用して、ヘルパーがこのような何かを生成したいのですが。

+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)

関連する問題