Scenario:
I have a partial view that is used in several places across my ASP.NET MVC application. The partial view contains a list of "objects" to select, i.e. something similar to:
<ul>
<%
foreach (var person in Model.Persons)
{
%>
<li><a href="#" class="person">
<%= person.Name %></a></li>
<%
}
%>
</ul>
Each person has a unique id.
I use jQuery for my AJAXy stuff, and up until now I have added click functionality to the links in the following way (although it has a very non-jQuery-like smell)
<a href="#" class="person" onclick="return selectPerson('<%= person.Id %>');">
<%= person.Name %></a>
It works and all, however it also requires me to have a selectPerson() javascript function on each page using this partial view (since what happens in the select is "special" for each view).
I just stumbled upon the jQuery Data() method and it seems to be able to support my needs, i.e. in the views using my partial person list view I could do something like:
$("a.person").click(function() { alert($(this).data("personId")); return false; });
If I have the Id's attached to the "personId" data property on the DOM elements.
Now the problem I have is that I do the HTML rendering server side, but the attaching of the "personId" data property to the DOM elements must be done client side. I.e. either during the foreach loop or in a separate JS loop but I would prefer to avoid that.
Maybe I'm going down the wrong path, I dunno, but maybe somebody has a solution for this or maybe a better approach?
Edit (updated for clarity):
Somehow execute
$(select the "current" anchor).data("personId", set to value of person.Id);