我在部分视图中写过以下
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")' } } });
操作名称和控制器名称不固定,它们必须根据放置此部分视图的视图进行更改.我有函数来获取调用操作和控制器名称,但不知道如何在@ Url.Action中传递它们.
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));
更新:
看来,您只是想要获取当前的控制器和可以实现的操作:
@{ string currentAction = Html.ViewContext.RouteData.GetrequiredString("action"); string currentController = Html.ViewContext.RouteData.GetrequiredString("controller"); }
接着:
window.location.href = '@Url.Action(currentAction,currentController)';