2016-03-25 21 views
-1

ASP.NET MVC ve Önyükleme ile bir uygulama yapıyorum. Benim uygulamasında, ben şöyle bir Modeli ile bakmaktadır:ASP.NET MVC - Özel HTML Yardımcısı'nda Modeli Kullanma

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

Ben:

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; } 
} 

Bu uygulamada, ben de şöyle bir özel html yardımcı tanımladığınız Bu gibi benim Jilet görünümünde bu yardımcı ve modelini kullanıyorum:

@model EntryModel 
<h2>Hello</h2> 

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

Ben özelliklerinden yardımcısında labelValue, controlId ve propertyValue değerlerini üretmek çalışıyorum Modelin

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

Esasen, benim html yardımcı içine benim modeli bilgi almak için emin değilim: Mesela ben @Html.MyTextBoxFor(m => m.Name) kullanmak ve yardımcı böyle bir şey üretmek olmasını istiyorum.

+0

kesinlikle yazılı heplers yapma öğrenmek [burada] (http://www.codeproject.com/Tips/389747/Custom-Strongly-typed-HtmlHelpers-in-ASP-NET-MVC) –

+0

@KartikeyaKhosla - Ama buradaki verileri mülkiyet? –

cevap

0

kullanın referans olarak bu örnek:

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

Ve böyle görünümünde çağırabilirsiniz: @ Html.AutoSizedTextBoxFor (x => x.Address2)