Getting the names of previous action and controller in MVC controller

廉价感情. 提交于 2019-12-06 02:13:38

问题


I can get the name of current action and controller like :

string controllername = this.ValueProvider.GetValue("controller").RawValue.ToString();
string actionname = this.ValueProvider.GetValue("action").RawValue.ToString();

Also I can get the reffer url by something like : string MyReferrer = Request.UrlReferrer.ToString();

But how can I get the names of previous action and controller in the mvc2 controller?


回答1:


This should work!

// Home is default controller
var controller = (Request.UrlReferrer.Segments.Skip(1).Take(1).SingleOrDefault() ?? "Home").Trim('/'); 

// Index is default action 
var action = (Request.UrlReferrer.Segments.Skip(2).Take(1).SingleOrDefault() ?? "Index").Trim('/'); 



回答2:


asp.net mvc does not provide this, due to stateless nature of http, but you can store this using session or cookie




回答3:


My first attempt would be to parse the previous path from the Referring URL in the request object.




回答4:


Store this value in tempdata OR look up the referring route (via the url) to get the actual route object, then look at its controller and action property. In order to get this you need to be able to look up a route from a URL. To do this, refer to Phil Haacks code (there are others as well) to look up a route. There are various methods listed at:

http://blogs.msdn.com/b/simonince/archive/2011/01/28/unit-testing-asp-net-mvc-routes.aspx




回答5:


Consider using ASP.NET MVC TempData.

http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

It will give you persistence across the current request and the next one, so you can store there routing information, like the last action called.

Data in TempData will be release from memory after the next request has been processed (in opposite to the ASP.NET Session object, that will release memory on Session timeout or termination).



来源:https://stackoverflow.com/questions/7087663/getting-the-names-of-previous-action-and-controller-in-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!