如何获取页面的ASP.NET MVC操作(即来自URL的操作)而不是当前操作?

时间:2022-11-30 22:42:57

Given the following simplified ASP.NET MVC scenario:

鉴于以下简化的ASP.NET MVC场景:

  1. A user navigates to a page http://www.mysite.com/Home/Index ("Index" explictly included for clarity)
  2. 用户导航到页面http://www.mysite.com/Home/Index(为清晰起见,明确包括“索引”)
  3. On that page is a $.ajax({..}) jQuery post that calls a method within Home controller, e.g. /Home/GetProducts
  4. 在该页面上是一个$ .ajax({..})jQuery帖子,它调用Home控制器中的方法,例如/主页/的GetProducts
  5. In the GetProducts() method I need to get the Index action name - bear in mind that at runtime I don't know whether the user is browsing Home/Index, Home/About, Home/Contact, etc., as GetProducts could be called from anywhere.
  6. 在GetProducts()方法中,我需要获取Index操作名称 - 请记住,在运行时我不知道用户是否正在浏览Home / Index,Home / About,Home / Contact等,因为GetProducts可能是从任何地方打来

I can't for the life of me get the page action (e.g. Index, About, Contact, etc.) in the scope of the GetProducts() method.

我不能为我的生活获取GetProducts()方法范围内的页面操作(例如索引,关于,联系等)。

I have tried the following:

我尝试过以下方法:

// returns "GetProducts"
string actionName1 = RouteData.GetRequiredString("action");
// returns "GetProducts"
string actionName2 = ControllerContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
// ParentActionViewContext == null
string actionName3 = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();

1 个解决方案

#1


1  

You can't get it. HTTP is a stateless protocol which doesn't keep any track of previous requests. So simply pass it as parameter to the AJAX request:

你无法得到它。 HTTP是一种无状态协议,它不会跟踪先前的请求。因此,只需将其作为参数传递给AJAX请求:

$.ajax({
    url: '@Url.Action("GetProducts", "Home")',
    data: { currentAction: '@ViewContext.RouteData.GetRequiredString("action")' },
    success: function(result) {
        // do something with the results
    }
});

and your GetProducts controller action will take it as parameter:

并且您的GetProducts控制器操作将把它作为参数:

public ActionResult GetProducts(string currentAction)
{
    ...
}

#1


1  

You can't get it. HTTP is a stateless protocol which doesn't keep any track of previous requests. So simply pass it as parameter to the AJAX request:

你无法得到它。 HTTP是一种无状态协议,它不会跟踪先前的请求。因此,只需将其作为参数传递给AJAX请求:

$.ajax({
    url: '@Url.Action("GetProducts", "Home")',
    data: { currentAction: '@ViewContext.RouteData.GetRequiredString("action")' },
    success: function(result) {
        // do something with the results
    }
});

and your GetProducts controller action will take it as parameter:

并且您的GetProducts控制器操作将把它作为参数:

public ActionResult GetProducts(string currentAction)
{
    ...
}