我在“使用条款”页面的几个翻译的顶部有这个:
<li><a href="@Url.Action("Index","Terms")">English</a></li> <li><a href="@Url.Action("Index","Terms","de")">Deutsch</a></li> <li><a href="@Url.Action("Index","fr")">Français</a></li> <li><a href="@Url.Action("Index","it")">Italiano</a></li> <li><a href="@Url.Action("Index","nl")">Nederlands</a></li> <li><a href="@Url.Action("Index","hu")">Maygar</a></li> <li><a href="@Url.Action("Index","es")">Español</a></li> <li><a href="@Url.Action("Index","zh")">简体中文</a></li> <li><a href="@Url.Action("Index","pt-pt")">European Português</a></li> <li><a href="@Url.Action("Index","pt")">Português</a></li>
这是应该处理点击的操作:
public class TermsController : Controller { public ActionResult Index(string id) { switch (id) { case "de": return View("de"); case "fr": return View("fr"); case "it": return View("it"); case "nl": return View("nl"); case "hu": return View("hu"); case "es": return View("es"); case "zh": return View("zh"); case "pt": return View("pt"); case "pt-pt": return View("pt-pt"); default: return View(); } }
这些是我的路线:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Terms","{controller}/{id}",new { controller = "Terms",action = "Index" } ); routes.MapRoute( "Default","{controller}/{action}/{id}",new { controller = "Home",action = "Index",id = "" } ); routes.MapRoute( "ThankYou","{controller}/{action}/{email}/{id}" ); }
从主要(即英语)条款页面,第一个(即英语)链接看起来是正确的:
http://localhost:65391/Terms/
为什么其他(即外国)生成的URL看起来像这样?
http://localhost:65391/Terms/?Length=2
奇怪的是,如果我手动输入
http://localhost:65391/Terms/de
例如,转到德语的“条款”页面,然后第一个超链接(即返回“英语条款”页面)如下所示:
http://localhost:65391/Terms/de
到这里查看实际网站:
解决方法
您正在使用Url.Action的
an overload,它将第三个参数视为routeValues对象.
来自MSDN:
routeValues
Type: System.Object
An object that contains the parameters
for a route. The parameters are retrieved through reflection by
examining the properties of the object. The object is typically
created by using object initializer Syntax.
所以你已经将字符串“de”,“fr”作为第三个参数传递,因此MVC已经获取了它的属性并创建了键值对:这就是Length = 2的来源,因为字符串类有一个属性Length,值是2为你的字符串.
您可以通过传递包装字符串的匿名对象来轻松解决此问题:
<li><a href="@Url.Action("Index","Terms" new { id = "" })">English</a></li> <li><a href="@Url.Action("Index",new { id = "de" })">Deutsch</a></li> <li><a href="@Url.Action("Index",new { id = "fr" })">Français</a></li> ...
笔记:
>您的匿名对象属性名称ID应与您的路段名称ID和控制器参数名称ID匹配>你需要expicilty在默认情况下传递新的{id =“”}否则MVC将使用已经给定的路由值.这是你在http:// localhost:65391 / Terms / de case中看到的.所以英文链接变成了http:// localhost:65391 / Terms / de,因为MVC已经在URL中找到了id值并自动重用它.>最后注意正确的拼写是Magyar而不是Maygar