jquery - 如何在@Url.Action中传递动态值?

标签 jquery asp.net-mvc-4 url.action

我在我的部分 View 中编写了以下 jquery:

    $.ajax({
        type: "POST",
        url: '@Url.Action("PostActionName", "ControllerName")',
        data: { Id: "01" },
        success: function(data)
            {
            if (data.success="true")
                {
                    window.location = '@Url.Action("GetActionName", "ControllerName")'
                }
            }
    });

Action 名称和 Controller 名称不是固定的,它们必然会根据放置此部分 View 的 View 而变化。我有函数来获取调用操作和 Controller 名称,但不确定如何在 @Url.Action 中传递它们。

以下是用于获取操作和 Controller 名称的 Javascript 函数:

function ControllerName() {
            var pathComponents = window.location.pathname.split('/');
            var controllerName;
            if (pathComponents.length >= 2) {
                if (pathComponents[0] != '') {
                    controllerName = pathComponents[0];
                }
                else {
                    controllerName = pathComponents[1];
                }
            }
            return controllerName;
        }

        function ActionName() {
            var pathComponents = window.location.pathname.split('/');
            var actionName;
            if (pathComponents.length >= 2) {
                if (pathComponents[0] != '') {
                    actionName = pathComponents[1];
                }
                else {
                    actionName = pathComponents[2];
                }
            }
            return actionName;            
        }

最佳答案

I have functions to fetch invoking action and controller names, but not sure how I can pass them in @Url.Action

嗯,你可以调用这些函数。例如,如果它们是 UrlHelper 类的扩展方法:

window.location = '@Url.Action(Url.MyFunction1(), Url.MyFunction2())'

或者如果它们只是静态函数:

window.location = '@Url.Action(SomeClass.MyFunction1(), SomeClass.MyFunction2())'

另一方面,如果需要传递的值仅在客户端上已知,您可以执行以下操作:

var param = 'some dynamic value known on the client';
var url = '@Url.Action("SomeAction", "SomeController", new { someParam = "__param__" })';
window.location.href = url.replace('__param__', encodeURIComponent(param));
<小时/>

更新:

看来您只是想获取当前的 Controller 和操作,可以这样实现:

@{
    string currentAction = Html.ViewContext.RouteData.GetRequiredString("action");
    string currentController = Html.ViewContext.RouteData.GetRequiredString("controller");
}

然后:

window.location.href = '@Url.Action(currentAction, currentController)';

关于jquery - 如何在@Url.Action中传递动态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052704/

相关文章:

javascript - JavaScript 代码出错?

javascript 或 jquery - 获取 href 的最后 2 个字符

javascript - 为什么当用户在其外部单击时此 div 不隐藏?

c# - 验证输入的日期是否早于今天的日期

c# - Rotativa PDF MVC3 分页

asp.net-mvc - 表单例份验证 cookie 未过期

javascript - 如何比较twig值和JS值?

asp.net-mvc - Razor MVC4 Url.Action 不起作用

jquery - url.action、jquery 和 mvc

c# - Url.Action 返回浏览器中的当前链接