h3n
h3n

Reputation: 5248

How to extend html.textboxfor to remove the name attribute?

I want to extend the helper to make it like this:


@html.TextBoxFor(x=>x.CustomerId).ReadOnly()

and output the input element without the name attribute, so that it will not be posted to the server.

Upvotes: 4

Views: 2323

Answers (2)

Mariusz Pawelski
Mariusz Pawelski

Reputation: 28792

You can't do it.

(at least without some ugly workarounds with processing string value returned from helper)

Html helpers were written to help you generate form fields for your model with intention that they will sent data to server. For strongly-typed helper (like Html.TextBoxFor(x => x.CustomerId)) the name is taken from passed expression and for not strongly-typed helpers (like Html.TextBoxFor("CustomerId", Model.CustomerId)) there is a check that throws exception when name is null or empty.

If you want to generate input without "name" attribute then simply do not use html helper methods.

For example, if you want to change you html helper usage to generate same output but without "name" attribute then:

  1. instead of this:
@Html.TextBoxFor(x => x.BetAmount)
  1. write this:
<input type="text" value="@Model.BetAmount" />
  1. instead of this:
@Html.TextBoxFor(x => x.BetAmount, new { @class = "red", placeholder = "Type Stuff", data_maximum_value = Model.MaximumBetAmount })
  1. write this:
<input type="text" value="@Model.BetAmount" class="red" placeholder="Type Stuff" data_maximum_value="@Model.MaximumBetAmount" />
  1. instead of this (you use overload with "format" argument):
@Html.TextBoxFor(x => x.BetAmount, "{0:0}", new { @class = "blue" })
  1. write this:
<input type="text" value="@Html.FormatValue(Model.BetAmount,"{0:0}")" class="red" />

because Html.TextBoxFor uses Html.FormatValue when you pass "format" argument.

This is not exactly the same what html helper do because html helpers first tries to get data from ModelState for validation purpose (it's a common gotcha). But for 99% of times this is probably good enough

I recommend checking actual source code of ASP.NET MVC if you want to know what helper methods are actually doing. It's not black magic.

Upvotes: 0

motime
motime

Reputation: 564

This should do the trick:

public static class MyInputExtensions
{
    public static MvcHtmlString NameLessTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        var textBox = htmlHelper.TextBoxFor(expression);

        string pattern = @"name=""([^""]*)""";

        string fixedHtml = Regex.Replace(textBox.ToHtmlString(), pattern, "");

        return new MvcHtmlString(fixedHtml);
    } 
}

Usage:

@Html.NameLessTextBoxFor(x=> x.CustomerId)

Upvotes: 3

Related Questions