Url.Action错误不存在对象

时间:2016-01-18 14:03:58

标签: javascript jquery ajax asp.net-mvc

我有脚本

$(function() {
    $.support.cors = true;
    jQuery.support.cors = true;
    $.ajax({
        crossDomain: true,
        type: 'GET',
        url: 'http://example.com/WCFRESTService.svc/GetCategories',
        success: function(result) {
            var s = '';
            for (var i = 0; i < result.length; i++) {
                s += '<br><a href="@Url.Action("GetAnn", "Home",new { categories_id=result[i]["Categories_id"]})">' + result[i]["Name_Category"] + '</a>';
                $('#content').html(s);
            }
        }
    });
});

Url.Actionresult[i]["Categories_id"]上出错。

  

名称&#34;结果&#34;在当前上下文中不存在

如何转移到我的对象结果?

1 个答案:

答案 0 :(得分:3)

您无法将JavaScript(客户端)变量传递给Url.Action,因为它是在服务器端处理的。

作为解决方法,您可以使用占位符来生成网址。然后使用.replace()方法生成实际网址。

var s = '';
//Generate a variable with URL
var url = '@Url.Action("GetAnn", "Home", new { categories_id = -1})'; 
for (var i = 0; i < result.length; i++) {
    s += '<br><a href="' + url.replace(-1, result[i]["Categories_id"]) + '">' + result[i]["Name_Category"] + '</a>';
    $('#content').html(s);
}