Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the names of previous action and controller in MVC controller

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

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

And I can also get the referring URL with something like this:

string MyReferrer = Request.UrlReferrer.ToString();

But how can I get the names of previous action and controller in an MVC 2 controller?

like image 948
eno Avatar asked Aug 17 '11 03:08

eno


People also ask

Can we have two action methods with same name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.

What is the name of the default action in an MVC controller?

By default, the Index() method is a default action method for any controller, as per configured default root, as shown below. routes. MapRoute( name: "Default", url: "{controller}/{action}/{id}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter. Optional });

How can we detect that an MVC controller is called by post or get?

You can check the Request. HttpMethod property.


1 Answers

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('/'); 
like image 124
jwize Avatar answered Sep 22 '22 18:09

jwize