给定以下简化的 ASP.NET MVC 场景:
- 用户导航到页面http://www.mysite.com/Home/Index (为清楚起见,明确包含“索引”)
- 在那个页面上是一个
$.ajax({..}) jQuery 帖子,它调用 Home 控制器中的一个方法,例如/Home/GetProducts - 在该
GetProducts()方法中,我需要获取 Index 操作名称 - 请记住,在运行时我不知道用户是否正在浏览Home/Index、Home/About、Home/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();