ASP.NET MVC - How to Change Textboxfor’s "Name" Attribute

Asked

Viewed 1,761 times

1

You can change the name of the field generated by @Html.TextBoxFor ? I found nothing in Portuguese related to this.

I tried something like:

@Html.TextBoxFor(x => x.ToDate, new { name = "to" })

If I do for example, for ID or Style:

@Html.TextBoxFor(x => x.ToDate, new { style = "display: none;", id = "to" })

Works for the two above, but not for the name.

So there is a way to change the name generated by default by @Html.TextBoxFor ?

  • You can write a Html Helper for this but, if you change the name will not be possible to post the form, the MVC will not take the value of the field to the Model, you don’t want that right? In that case it wouldn’t be easier to declare a input simple instead of using the Helper Html.TextBoxFor?

  • But my intention is not to use with the model, but with parameters, separate from the same model.

  • So if you don’t want to use the model, why not use an element htmlthen? Then you can put the name you want. The helper @Html.TextoBoxFor is to be used thinking of Binding and model post on MVC

  • I use a model in the view, for a form, but also another form that uses one or another data that is filled in the template, but not all model data.

2 answers

1


This attribute is case sensitive.

Use Name rather than name:

@Html.TextBoxFor(x => x.ToDate, new { Name = "to" })

Another example:

@Html.TextBoxFor(x => x.MeuCampo, new { Name = "blabla" })

inserir a descrição da imagem aqui

  • This is not a solution because it will not change the name of html but will create another attribute with Name, which is an invalid HTML. It can work only because some browsers ignore the second name and consider only the first.

  • Reading the text of the question "You can change the name of the field generated by @Html.Textboxfor?" and the other question "Then there is a way to change the name generated by @Html.Textboxfor by default ?" understood that he needs to change the name of the field. If it is not that, maybe it would be interesting to supplement/edit the question.

0

As follows it is possible to change the name of Textboxfor

       @Html.TextBoxFor(x => x.ToDate, new
       {
           htmlAttributes = new
           {
               @class = "form-control",
               style = "display:none;",
               id = "to",
               name = "to"
           }
       })
  • Is it not identified that new { name = "to"} is an htmlAttributes ? Just as it does for id and style?

  • I don’t understand your question

  • If I do new { id= "to"}, it identifies that this is an htmlAttributes. But for what reason new { name = "to"}, does it not ? For your example, it would basically repeat this, only explicitly, right ?

  • I don’t know why it works that way and not the other way, I had the same problem and only that way it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.