假设我有一堂课
public class ItemController:Controller { public ActionResult Login(int id) { return View("Hi", id); } }
在不位于 Item 文件夹的页面上ItemController,我想创建一个指向该Login方法的链接。那么Html.ActionLink我应该使用哪种方法,应该传递哪些参数呢?
ItemController
Login
Html.ActionLink
具体来说,我正在寻找方法的替换
Html.ActionLink(article.Title, new { controller = "Articles", action = "Details", id = article.ArticleID })
已在最近的 ASP.NET MVC 化身中退役。
我想你想要的是这样的:
Html.ActionLink(article.Title, "Login", // <-- Controller Name. "Item", // <-- ActionMethod new { id = article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). )
这使用以下方法 ActionLink 签名:
public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string controllerName, string actionName, object values, object htmlAttributes)
两个论点被调换了
Html.ActionLink(article.Title, "Item", // <-- ActionMethod "Login", // <-- Controller Name. new { id = article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). )
public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object values, object htmlAttributes)
参数的顺序与 MVC2 相同,但不再需要 id 值:
Html.ActionLink(article.Title, "Item", // <-- ActionMethod "Login", // <-- Controller Name. new { article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). )
这避免了将任何路由逻辑硬编码到链路中。
<a href="/Item/Login/5">Title</a>
这将为您提供以下 html 输出,假设:
article.Title = "Title"
article.ArticleID = 5
. .
routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults );