Beetlejuice
Beetlejuice

Reputation: 4425

Custom TextBox Asp.net MVC Helper with wrapper

i want to create my own TextBox Helper that do a simple thing: wraps the input element with some divs and labels, like this:

<div class="col-xs-12">
  <label>field name</label>
  <div>
    <input id='myId' name='MyName' type='text' value='myValue'>
  </div>
</div>

In the view, i want to call it this way:

@Html.TextBox("Name")

How can I do this? There is a way to call base class in my helper?


Update: a better solution

After Krishina answer, I got a better approach, using code like this:

public static MvcHtmlString CliTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string LabelText, object htmlAttributes)
    {
        var baseFormat = htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: htmlAttributes);
        var errors = htmlHelper.ValidationMessageFor(expression, "", new { @class = "text-danger" }).ToString();

        if (!string.IsNullOrEmpty(errors))
            errors = "<div>" + errors + "</div>";

        var wrap = String.Format(
            "<div class='col-xs-12'>" +
            "<label>{0}</label>" +
            "<div>{1}</div>"+
            "{2}" +
            "</div>", LabelText, baseFormat.ToString(), errors);

        return new MvcHtmlString(wrap);
    }

In this way, I keep using TextBoxFor to generate the base input element.

Upvotes: 4

Views: 2630

Answers (1)

Venkata Krishna
Venkata Krishna

Reputation: 15112

You need to create a custom Html Helper for your textbox like below.

namespace MvcApplication.Helpers
{
    public static class TextboxExtensions
    {
        public static HtmlString CustomTextBox(this HtmlHelper helper, string labelName, NameValueCollection parameters)
        {
            var returnValue = string.Empty;
            if (parameters == null || parameters.Count <= 0) return new HtmlString(returnValue);

            var attributes = parameters.AllKeys.Aggregate("", (current, key) => current + (key + "=" + "'" + parameters[key] + "' "));

            returnValue = String.Format("<div class='col-xs-12'><label>{0}</label>" +
                                        "<div><input " + attributes + "></div></div>", labelName);

            return new HtmlString(returnValue);
        }
    }
}

And to use the above extension method, follow these steps

In your MVC view, write the using statement on top

@using MvcApplication.Helpers

And, write the Html helper as follows

@Html.CustomTextBox("Name", new NameValueCollection { {"id", "myId"}, {"value", "myValue"} })

Note: You could use json or some other type instead of NameValueCollection.

Upvotes: 2

Related Questions