Razor View 中的 Javascript url 操作

标签 javascript asp.net-mvc-3 razor

我有一个获取 rowid 的 javascript 方法 onRowSelected。如何使用 HttpGet 在 Controller 的某些操作中传递 rowid?

function onRowSelected(rowid, status) {
        alert('This row has id: ' + rowid);
        //url: @Action.Url("Action","Controller")
        //post:"GET"
        // Something like this?
    }

最佳答案

如果您的 Controller 操作需要一个 id 查询字符串参数:

var url = '@Url.Action("Action", "Controller")?id=' + rowid;

或者如果你想将它作为路由的一部分传递,你可以使用 replace:

var url = '@Url.Action("Action", "Controller", new { id = "_id_" })'
    .replace('_id_', rowid);

如果您要发送 AJAX 请求,还有另一种可能性是将其作为 POST 正文的一部分传递:

$.ajax({
    url: '@Url.Action("Action", "Controller")',
    type: 'POST',
    data: { id: rowid },
    success: function(result) {

    }
});

或者如果您使用 GET,则作为查询字符串参数:

$.ajax({
    url: '@Url.Action("Action", "Controller")',
    type: 'GET',
    data: { id: rowid },
    success: function(result) {

    }
});

当然,所有这些都假设您的 Controller 操作采用 id 参数:

public ActionResult Action(string id)
{
    ...
}

因此您可以看到实现同一目标的多种方法。

关于 Razor View 中的 Javascript url 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11599995/

相关文章:

javascript - Material-UI 更改抽屉颜色

javascript - 错误!代码 E503

c# - 将鼠标悬停在条形图上时使用 ASP.NET MVC 3.0 显示列标签

c# - 将 JSON 字符串反序列化为 C# 对象

javascript - 包含的 Javascript 中的 Razor 标签(在单独的文件中)?

linq-to-sql - 在Razor View 中使用System.Data.Linq

javascript - 如何导出加密 key ?

javascript - 如何在 Sails.js 中嵌入和编写 mongo 对象(不止一层深)?

asp.net-mvc-3 - 如何使用 JQuery 和 tokenInput 触发 Controller

jquery - MVC Razor动态构建onclick事件以显示模态