我是 MVC 和 JQuery 新手。
我已经用 JQuery 创建了一张表,但我不知道如何添加一个 actionlink
在每一行中,我还需要调用 onclick
上的一个部分 View 通过将 Java 脚本变量传递给分部 View 来事件。
我的代码如下:
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td>' + '@Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
tab.append(trow);
});
这里我遇到一个错误:
val is not in the current context
我在这里检查了很多类似的帖子,我了解代码的一部分是在服务器上运行的(Url.Action
部分)和val.empID
部分。仅当代码到达客户端浏览器后才可用。
但是如果有任何替代方法可以执行此操作,我需要在单击时加载一个部分 View ......
最佳答案
您无法将客户端 JavaScript 变量传递给服务器端帮助程序函数。
当@Html.ActionLink
创建 anchor 标记时,您可以通过编程方式创建它。这是一个例子:
function loadData(data) {
$.each(data, function(i, val) {
//Create Static URL and use -1 as placeholder
var url = '@Url.Action("actionName", "controllerName", new { id = -1 })';
//replace the place holder with the value which you want
url = url.replace('-1', val.empID);
//Generate the anchor
var anchor = '<a class="myClass" href="' + url + '">Edit</a>'
//Append anchor
trow.append('<td>' + anchor + '</td>');
tab.append(trow);
});
}
$(document).on('click', '.myClass', function(evt) {
evt.preventDefault();
//Code to load your partial view
$('#myDiv').load(this.href);
});
关于javascript - 通过ajax actionlink传递javascript变量来加载部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139670/