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.
Asked
Active
Viewed 1,277 times
0
-
Check Http context's RouteData's `action` and `controller`. – Wiktor Zychla May 28 '18 at 12:00
-
A view model has no relation to the view nor action. Either set it yourself in the controller, or look it up in the RouteData in the validator. – CodeCaster May 28 '18 at 12:01
-
How do I do the latter, look up/get access to the RouteData? – Thorkil Værge May 28 '18 at 12:10
-
@ThorkilVærge why do you care? What are you *actually* trying to do? If you want to validate anything input, use validation arguments and methods in the action itself and its ViewModel. If you want to restrict access to an action look into authentication – Panagiotis Kanavos May 28 '18 at 14:48
-
1@ThorkilVærge different edit vs display validations or edit vs new are also available. The techniques are described in most tutorials. Usually though it's better to use *different* ViewModels and map between them eg with Automapper. Trying to get the same ViewModel to serve different/contradicting requirements leads to unnecessary complexity – Panagiotis Kanavos May 28 '18 at 14:51
-
I have learnt now that different view models are preferred. But it takes time to rewrite that part of the code :) – Thorkil Værge May 29 '18 at 10:37
2 Answers
1
You can add a property in your viewmodel that contains what it is used for. You can set this in the controller.

sander
- 719
- 2
- 9
- 21
-
That is a fine idea but does that not allow the user to change it? – Thorkil Værge May 28 '18 at 12:01
-
1You can put it in a hidden field, but yes, a smart user (legend has it, that they exist), could find the hidden field in your HTML and change its value there – sander May 28 '18 at 14:06
1
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"))
{
...
}

Andrew
- 7,602
- 2
- 34
- 42