ASP.NET MVC - 我可以为同一个动作创建多个名称吗?
在同一个控制器中......我可以为同一个动作设置多个名称吗?
我正在寻找一个完整的多语言解决方案.基本上我希望所有的逻辑都相同,但根据语言改变"关键字"(动作,URL中的控制器).
您不能为同一操作使用多个名称.这将是不同的行动.这就是mvc的工作方式.Mabe最好用路由实现所描述的行为.
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 }
);
Run Code Online (Sandbox Code Playgroud)
当然,您必须创建许多路径,但您可以在数据库中创建配置文件或存储路由数据,并在应用程序启动时循环创建它们.无论如何,我认为它比创建方法更好,因为如果你想要添加一种语言,你需要在你的控制器上找到动作并重新编译代码.但是在路由和配置文件的情况下 - 它变得不那么难.第二件事是Html.ActionLink("Home","Index","Home")扩展 - 您必须实现自己的返回本地化操作链接.
我知道我迟到了,但如果有人在谷歌搜索,我创建了一个匹配多个名称的属性(灵感来自 ActionName 属性),如下所示:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
[ActionNames("CreateQuickItem", "CreateFullItem")]
public ActionResult Create() {}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8694 次 |
最近记录: |