3

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.

Maksim Vi.
  • 9,107
  • 12
  • 59
  • 85
  • You can reduce the occurrence of this problem by using editor templates. To control the behavior yourself, you can set `ViewData.TemplateInfo.HtmlFieldPrefix`. You then need to instruct the model binder what prefix you used, so this can get tricky if you are mixing field prefixes. Example: `public ActionResult _Edit( [Bind( Prefix = "MyPrefix" )] AModel model )` – Tim M. Jan 17 '14 at 21:40
  • It looks like that will require passing whole models inside actions (or duplicating actions), which doesn't look like a good approach in my case. – Maksim Vi. Jan 17 '14 at 22:23

2 Answers2

0

Try to use :

    @Html.TextBoxFor(m => m.id,new {@class="class",id=[but here the id you want]})
Shhade Slman
  • 263
  • 2
  • 10
0

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.

Romias
  • 13,783
  • 7
  • 56
  • 85
  • My bad, I guess I didn't explain the problem well. My view models are not composed. They are separate. Let's say I have `Employee` edit view on a page with `Id, Name, etc` fields and via ajax on the same page the user decided to load a form to create a new `Department` with `Id, Name, etc` fields. Let's assume that `Employee` and `Department` controllers are unrelated. – Maksim Vi. Jan 20 '14 at 18:55
  • OK. Then, as in the views you are supposed to use ViewModels, you have all the freedom to rename the properties using a prefix... then the models can remain with the properties with its original duplicated values. This is not a tech suggestion, but will work :) – Romias Jan 20 '14 at 20:34