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

后端 未结 2 1022
闹比i
闹比i 2020-12-19 15:05

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


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

and output the input element without the

相关标签:
2条回答
  • 2020-12-19 15:23

    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)
    
    0 讨论(0)
  • 2020-12-19 15:35

    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.

    0 讨论(0)
提交回复
热议问题