Implementing Jquery-autocomplete resource with MVC Controls toolkit

May 23, 2011 at 1:28 PM

Hello everyone!

I'm developing my first ASP.NET MVC application and I'm using MVC Controls Toolkit.

I also need to implement an autocomplete resource for one input text in this data grid, which I could do using JQuery if I was able to get the id generated for each input in my data grid when my view is rendered, including the empty one that is used to insert a new register.

Looking at the html code generated when I run the application I can see that the id is like this

    id="ToDoList___0___Item_Value_Name" //First item
id="ToDoList___1___Item_Value_Name" //Second item
id="ToDoList___2___Item_Value_Name" //Empty item - new register

My jquery script is:

    $(document).ready(function() {
$("#myDynamicFieldId).autocomplete('@Url.Action("GetTags")');
});
......

Does anyone know how can I tell my Jquery script what is the current Id?

Thanks,

Natali

Coordinator
May 24, 2011 at 12:30 PM

I Advice don't caring "How id are generated" but just to know what a id is. This is because the id may depend on the whole path in the ViewModel of the property being rendered in the grid, and also on possible  in-line transformation applied, and if the grid is in a partial view....and so on. 

If you are either in a row template or in a column template you can get the id of a field associated say to a property called say "Name", by calling the PrefixedId helper with something like:

Html.PrefixedId("Name") or item.PrefixedId("Name") or similar according to the name of the variable that contain the name of the HtmlHelper that is associated to the template or partial view you are in.

So if we suppose you are in a row template and and you are using an in-line html razor helper as template your code becomes:

$(document).ready(function() {
$("#"+'@item.PrefixedId("Name")').autocomplete('@Url.Action("GetTags")');
});

HOWEVER YOU MUST PUT THE ABOVE CODE IN THE COLUMN OR ROW TEMPLATE because on outer scoper "Name" is not defined. If you don't kno exactly what a template is please read doc about templates: http://mvccontrolstoolkit.codeplex.com/wikipage?title=Use%20of%20Templates