Thorkil Værge
Thorkil Værge

Reputation: 3787

Get current action in mvc view model

I have a view model that is shared between several actions. Is it possible to get the name of the action that is being called and, if so, how do I achieve that. I need the name of the action inside a custom validator function.

Upvotes: 0

Views: 1415

Answers (2)

Andrew
Andrew

Reputation: 7880

Not sure if this could be of use for you, but if you need to access it from the view, you can do that by accessing this:

(string)Html.ViewContext.RouteData.Values["action"]

If you will need that often, you can create an extension method like this:

public static string GetAction(this HtmlHelper helper)
{
    return (string)helper.ViewContext.RouteData.Values["action"];
}

And then simply do this in the view:

@{
    var action = Html.GetAction();
}

...
@if (action.Equals("YourAction"))
{
    ...
}

Upvotes: 1

sander
sander

Reputation: 749

You can add a property in your viewmodel that contains what it is used for. You can set this in the controller.

Upvotes: 1

Related Questions