ehsan
ehsan

Reputation: 364

how to add parameters to razor helpers

I want to know how write HTML Helper like @Html.TextBoxFor(model => model.signature) to have data-id parameter in produced input like below by helper.

<input type="text" name="signature"  data-id="No Signature" />

Note 1: parameter like dataId is work by htmlAttributes because it is a simple variable.

Note 2: I know extended method and use attribute like @{var attributes = new Dictionary<string, object>{{ "data-id", "No Signature" }};}

I feel that there must be a better way to solve this. Any idea...?

Thanks a lot.

Upvotes: 5

Views: 2904

Answers (3)

Ed Charbeneau
Ed Charbeneau

Reputation: 4634

The code below will create a CustomTextBoxFor helper by extending TextBoxFor. This allows you to take full advantage of MVC's validation conventions as well leaving open the htmlAttributes parameter so more attributes can be appended as needed.

        public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression, string customData)
        {
            return htmlHelper.CustomTextBoxFor(expression, customData, (IDictionary<string, object>)null);
        }

        public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
           Expression<Func<TModel, TProperty>> expression, string customData, object htmlAttributes)
        {
            IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            attributes.Add("data-custom", customData);
            return htmlHelper.TextBoxFor(expression, new { data_custom = "customData" });
        }

Usage:

@Html.CustomTextBoxFor(model => model.MyProperty, Model.CustomData)
@Html.CustomTextBoxFor(model => model.MyProperty, Model.CustomData, new { @class="pretty"})    

Upvotes: -2

Henk Mollema
Henk Mollema

Reputation: 46501

You can add data- attributes this way:

@Html.TextBoxFor(model => model.signature, new { data_id = "No signature" })

You have to use underscores (_) in stead of dashes (-).

Tip: it's also possible to use Model variables in your data- attributes:

new { data_id = Model.Id }

Upvotes: 4

Darren
Darren

Reputation: 70718

You can create your own custom helpers like:

 public static class TextBoxExtensions
     {
          public static string CustomTextBox(this HtmlHelper helper, string name)
          {
               return String.Format("<input type='text' name={0} data-id='No Signature'></input>", name);
          }
     }

Then in your View you can do:

@Html.CustomTextBox("signature");

Upvotes: 1

Related Questions