Add prefixes to id's and names of viewmodel fields

1.3k views Asked by At

In my project I use a lot of views/forms that are loaded dynamically. In my forms there are a lot of fields generated by using @Html.TextBoxFor() and then @Html.IdFor(), @Html.NameFor() are used in my javascript logic.

Some of my view models have fields with the same name (Id, Name, Description, etc), so if I have 2 forms with such view models on 1 page then I have a problem (same id attribute used for more than one element).

So I'm wondering if I can add some serverside metadata/attribute to my viewmodels with a prefix that will be added to generated id's and names? Or if there is another solution that doesn't require renaming my viewmodels or views.

2

There are 2 answers

2
Romias On

You could use the "name" attribute of your inputs in your javascript code... those attributes are generated automatically.

If you have a composed ViewModel like this:

public class MyViewModel{
   public MySecondModel Sencond {get; set;}
   public MySecondModel Third {get; set;}
}

public class MySecondModel {
   public string Name {get; set;}
   public string Description {get; set;}
}

Then you use it in your views like this:

@Html.TextBoxFor(x => x.Second.Name)
@Html.TextBoxFor(x => x.Third.Name)

The name attribute will became: "Second_Name" and "Third_Name"

So... it will not repeat.

0
Shhade Slman On

Try to use :

    @Html.TextBoxFor(m => m.id,new {@class="class",id=[but here the id you want]})