0

I am building an app with ASP.NET MVC and Bootstrap. In my app, I have a view with a Model that looks like this:

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

In this app, I've also defined a custom html helper that looks like this:

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

I'm using this helper and model in my Razor view, like this:

@model EntryModel
<h2>Hello</h2>

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

I am trying to generate the labelValue, controlId, and propertyValue values in the helper from the properties of the Model. For example, I'd like to use @Html.MyTextBoxFor(m => m.Name) and have the helper generate something like this:

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

Essentially, I'm not sure how to get my model information into my html helper.

Some User
  • 5,257
  • 13
  • 51
  • 93

1 Answers1

1

Use this example as reference:

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

And you can call it in the view like this: @Html.AutoSizedTextBoxFor(x => x.Address2)

univ
  • 717
  • 4
  • 12