Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Controller's Action name in View

What is the correct way to get the name of the Action returning the View in MVC3?

I am using ViewContext.Controller.ValueProvider.GetValue("action").RawValue to return the name of the Action (Method), which is creating the View in MVC3. I return this in a Partial View, which is included in the View returned by the Action.

It works fine for Index, but, when I try to use it for another method name, it always evaluates to false.

In the immediate window I get the following results:

ViewContext.Controller.ValueProvider.GetValue("action").RawValue
"Edit"

ViewContext.Controller.ValueProvider.GetValue("action").RawValue == "Edit"
false

Which is highly confusing, because the first statement evaluates to a string with value "Edit", while comparing this to a string "Edit" returns false?

Bizarre...

like image 548
Darbio Avatar asked Sep 25 '11 02:09

Darbio


People also ask

What is action name and controller name in MVC?

Actions are public methods in an MVC controller, that respond to a URL request. Action Selectors are attributes that can be applied to action methods and are used to influence or control which action method gets invoked in response to a request.

How do you access the variable of the controller in the view?

OK, the simple answer is, you need to know the . Net type being returned from your query when you set the scrap variable in your controller. Whatever that type is, that's what type your @model needs to be. Either that, or use the ViewBag --but again, without IntelliSense support since it's a dynamic .


1 Answers

RawValue is an object, so RawValue == "..." calls Object.op_Equality, which comparse by reference rather than by value.

Call ViewContext.RouteData.GetRequiredString("action")

like image 163
SLaks Avatar answered Sep 22 '22 12:09

SLaks