Using ASP.NET MVC and JQuery, how do I run a JS function for each item in the list on load?
Imagine a view for displaying a list of Foo items:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Foo>>" %>
The page now displays a list of elements of type Foo:
<table>
<tr>
<th>
Name
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.Name) %>
</td>
</tr>
<% } %>
</table>
In addition to displaying a list of items on the page, I also need to execute a Javascript function bar for each of the items. Here's my first try:
<% foreach (var item in Model) { %>
<script type="text/javascript">
$(document).ready(function() {
var name = "<%=item.Name %>";
Bar(name)
});
</script>
<% } %>
I am getting the error "Cannot resolve character element" on a line starting with "var name ...".
Is this the correct way to achieve this? What's the correct syntax to use?
a source to share
Try something like this:
<script type="text/javascript">
$(document).ready(function() {
$("table tr td").each(function() {
Bar(this.text());
});
});
</script>
This script should be static and not generated by your view. Place it at the top of the page, or place it in an external file and link it to that file.
a source to share
I'm not sure where your error is coming from (you may be using double quotes rather than single quotes for code blocks), but you also introduce a separate script element for each name. @ Andrew's method will work well, but you can also do something like below. It creates a javascript array (as a string) containing the names, then injects one script block that iterates over the elements of the array and calls the Bar function on each. I would use @Andrew's method if you need to interact with the DOM elements themselves, and perhaps this mechanism if you only need to interact with data.
<% string names = "[";
foreach (var item in Model)
{
names = names + item.Name + ",";
}
names = names.TrimEnd(',') + "]";
%>
<script type="text/javascript">
$(function() {
$.each( <%= names %>, function(i,val) {
Bar(val);
});
});
</script>
a source to share