我正在尝试传递从以下函数生成的列表;
public List<long> GetIDs()
{
var ids = new List<long>();
foreach(var s in student)
{
ids.Add(s.ID);
}
return ids;
}
并通过razor View 传递列表并在jquery中访问列表。
以下是 CSHTML 代码:
<a href="#" class="color-blue" data-studentids = "@schoolLicense.GetIDs()" onclick="sendWelcomeEmail(this)">
这是我想要访问列表并根据我获得的 ids 执行操作的 jquery 代码;
function sendWelcomeEmail(elem) {
$.each($(elem).attr("data-studentids"), function (index, value) {
alert(index + ": " + value);
});
}
但是我没有从列表中获取 Id,而是收到错误消息
TypeError: invalid 'in' operand obj
var length = !!obj && "length" in obj && obj.length,
谁能告诉我哪里出了问题吗?
最佳答案
你的问题是因为输出 List<string>
从您的 GetIDs
返回方法你只是将它强制为字符串。因此你的输出是:
<a href="#" data-studentids="System.Collections.Generic.List`1[System.Int64]" ...
要解决此问题,您可以 Join()
将数据放在一起,然后 split()
它返回到 JS 中的数组中。试试这个:
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);
});
});
请注意 GetIDs
中 LINQ 的简化使用方法,以及在 JS 中使用不显眼的事件处理程序。
您可以修改.colour-blue
jQuery 对象中的选择器可以更好地满足您的需求。我只是在本示例中使用了它,因为它是元素上唯一相关的属性。
关于c# - 将列表从 cshtml View 传递到 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628619/