stopcode.net

Dave Knipper Was Here

Generate "ASP.NET Web-FormLike" Unique Client Ids for Controls Within ASP.NET MVC

Here's a way to generate "ASP.NET Web-FormLike" unique client Ids for client controls within ASP.NET MVC.

1. Create a custom description attribute. This will be used later on properties within your model. Example: 2. Create or modify your model. The "Id" property is of course the unique Id for the model. The "IdPropertyFrom" string field contains the name of the property which contains the unique Id for the model. The ClientIdFromPropertyAttribute is used to tell the MVC Html Helper where to get the unique Id for the model (based on the "IdPropertyFrom" field name), and the property the MVC Html Helper needs to process (in this case the "Description"). 3. Create the MVC Html Helper Extension. This method will return a unique client control Id based on the model meta information from above by using reflection. At the end, a unique client control Id will be returned that looks something like this:

<model name>_<property name>_<unique id>

In this example (assuming the unique Id is 1), the client control id will look like:

MyModel_Description_1 4. Use in the view: