开发者

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 com开发者_JS百科plete multiple language solution. Essentially the i want all the logic to be sa same but change the "keywords" (actions, controllers in the url) depending on language.


You can't have multiple names for same action. It will be different actions. This is the way how mvc works. Mabe it's better to implement described behaviour with routing.

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 }
);

Ofcourse you'll have to create many routes, but you can make config file or store routing data in database, and just create them in loop on application start. Anyway I think it's better then creating planty of methods, becouse if you'll want to add one more language you'll need to find actions all over your controllers and recompile code. But in case of routes and config file - it become not so hard. Second thing is Html.ActionLink("Home", "Index", "Home") extension - you'll have to implement your own to return localized action link.


I know I'm late to the party but in in case someone is googling, I created an attribute (inspired from ActionName attribute) that matches multiple 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))
            {
                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));
    }
}

To use:

[ActionNames("CreateQuickItem", "CreateFullItem")]
public ActionResult Create() {}


I'm not sure if having multiple action names is possible. One way I could think of doing this is by defining multiple actions with different names that internal cal/execute the same action.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜