ASP.NET MVC - Can I have multiple names for the same action?

ASP.NET MVC - Can I have multiple names for the same action?

In the same controller ... Can I have multiple names for the same action?

I am looking for a complete solution for several languages. Essentially, I want the whole logic to be the same, but change the β€œkeywords” (actions, controllers in the URL) depending on the language.

+7
asp.net-mvc
source share
3 answers

You cannot have multiple names for the same action. These will be different actions. This is how mvc works. Mabe is better at implementing the described routing behavior.

routes.MapRoute("Lang1RouteToController1Action1", "Lang1Controller/Lang1Action/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute("Lang2RouteToController1Action1", "Lang2Controller/Lang2Action/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

Of course, you will need to create many routes, but you can create a configuration file or save routing data in a database and simply create them in a loop when the application starts. In any case, I think this is better than creating plant methods, because if you want to add another language, you will need to find actions on all your controllers and recompile the code. But in the case of routes and the configuration file, this is not so difficult. Secondly, the extension Html.ActionLink ("Home", "Index", "Home") - you will need to implement your own in order to return a link with a localized action.

+7
source share

I am not sure if it is possible to have multiple action names. One way that I could do this is to define several actions with different names that inside cal / perform the same action.

+2
source share

I know I'm late to the party, but in case someone works at Google, I created an attribute (inspired by the ActionName attribute) that matches several names as follows:

 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ActionNamesAttribute : ActionNameSelectorAttribute { public ActionNamesAttribute(params string[] names) { if (names == null) { throw new ArgumentException("ActionNames cannot be empty or null", "names"); } this.Names = new List<string>(); foreach (string name in names) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException("ActionNames cannot be empty or null", "names"); } this.Names.Add(name); } } private List<string> Names { get; set; } public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return this.Names.Any(x => String.Equals(actionName, x, StringComparison.OrdinalIgnoreCase)); } } 

For use:

 [ActionNames("CreateQuickItem", "CreateFullItem")] public ActionResult Create() {} 
+2
source share

All Articles