Appu Appu - 23 days ago 8
C# Question

Pass list from cshtml view to jquery function

Im trying to pass List that is generated from the following function;

public List<long> GetIDs()
{
var ids = new List<long>();
foreach(var s in student)
{
ids.Add(s.ID);
}
return ids;
}


and passing the list through the razor view and access the list in the jquery.

Following is the CSHTML code :

<a href="#" class="color-blue" data-studentids = "@schoolLicense.GetIDs()" onclick="sendWelcomeEmail(this)">


and this is the jquery code where I want to access the list and do actions from the ids I get ;

function sendWelcomeEmail(elem) {
$.each($(elem).attr("data-studentids"), function (index, value) {
alert(index + ": " + value);
});
}


But I'm not getting the Ids from the list instead of that I'm getting error as


TypeError: invalid 'in' operand obj

var length = !!obj && "length" in obj && obj.length,


Can anyone please let me know where Im going wrong?

Answer

Your problem is because by outputting the List<string> returned from your GetIDs method you're just coercing it to a string. Therefore your output is:

<a href="#" data-studentids="System.Collections.Generic.List`1[System.Int64]" ...

To fix this you can Join() the data together and then split() it back in to an array in your JS. Try this:

public List<long> GetIDs()
{
    return student.Select(s => s.ID).ToList();
}
<a href="#" class="color-blue" data-studentids="@String.Join(",", schoolLicense.GetIDs())">
$('.colour-blue').click(function(e) {
    e.preventDefault();
    $(this).data('studentids').split(',').forEach(v, i) {
        console.log(i + ": " + v);
    });
});

Note the simplified use of LINQ in the GetIDs method, and the use of the unobtrusive event handler in the JS.

You can amend the .colour-blue selector in the jQuery object to better match your needs. I simply used it in this example as it was the only relevant attribute on the element.