I want to extend the helper to make it like this:
@html.TextBoxFor(x=>x.CustomerId).ReadOnly()
and output the input element without the
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)
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:
@Html.TextBoxFor(x => x.BetAmount)
<input type="text" value="@Model.BetAmount" />
@Html.TextBoxFor(x => x.BetAmount, new { @class = "red", placeholder = "Type Stuff", data_maximum_value = Model.MaximumBetAmount })
<input type="text" value="@Model.BetAmount" class="red" placeholder="Type Stuff" data_maximum_value="@Model.MaximumBetAmount" />
@Html.TextBoxFor(x => x.BetAmount, "{0:0}", new { @class = "blue" })
<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.