【问题标题】:How do you get the ASP.NET MVC action of the page (i.e. one from URL) rather than current action?您如何获得页面的 ASP.NET MVC 操作(即来自 URL 的操作)而不是当前操作?
【发布时间】:2013-08-23 14:22:10
【问题描述】:

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

  1. 用户导航到页面http://www.mysite.com/Home/Index(为清楚起见,明确包含“索引”)
  2. 在那个页面上有一个 $.ajax({..}) jQuery 帖子,它调用 Home 控制器中的一个方法,例如/Home/GetProducts
  3. GetProducts() 方法中,我需要获取索引操作名称 - 请记住,在运行时我不知道用户是否正在浏览Home/IndexHome/AboutHome/Contact 等,如可以从任何地方调用GetProducts

我一辈子都无法在 GetProducts() 方法的范围内获取页面操作(例如索引、关于、联系人等)。

我尝试了以下方法:

// 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();

【问题讨论】:

  • 注意:我可以从调用视图传入动作名称,但我想避免这样做。
  • 抱歉,没有其他办法,由于 HTTP 协议的无状态特性,您将不得不这样做。

标签: asp.net-mvc routes


【解决方案1】:

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

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

您的GetProducts 控制器操作会将其作为参数:

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

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 2012-01-26
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多