Nir*_*man 17 jquery url.action asp.net-mvc-4
我在部分视图中写了以下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")'
}
}
});
Run Code Online (Sandbox Code Playgroud)
动作名称和控制器名称不固定,它们必然会根据放置此局部视图的视图而改变.我有获取调用操作和控制器名称的函数,但不知道如何在@ Url.Action中传递它们.
以下是用于获取操作和控制器名称的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;
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 30
我有获取调用操作和控制器名称的函数,但不知道如何在@ Url.Action中传递它们
好吧,你可以调用这些功能.例如,如果它们是UrlHelper类的扩展方法:
window.location = '@Url.Action(Url.MyFunction1(), Url.MyFunction2())'
Run Code Online (Sandbox Code Playgroud)
或者如果它们只是静态函数:
window.location = '@Url.Action(SomeClass.MyFunction1(), SomeClass.MyFunction2())'
Run Code Online (Sandbox Code Playgroud)
另一方面,如果只需要在客户端上知道需要传递的值,则可以执行以下操作:
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));
Run Code Online (Sandbox Code Playgroud)
更新:
看来你只是试图获取当前控制器和动作,可以这样实现:
@{
string currentAction = Html.ViewContext.RouteData.GetRequiredString("action");
string currentController = Html.ViewContext.RouteData.GetRequiredString("controller");
}
Run Code Online (Sandbox Code Playgroud)
然后:
window.location.href = '@Url.Action(currentAction, currentController)';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75338 次 |
| 最近记录: |