HTML.ActionLink 方法 [英] HTML.ActionLink method
问题描述
假设我有一堂课
public class ItemController:Controller
{
public ActionResult Login(int id)
{
return View("Hi", id);
}
}
在不位于 ItemController
所在的 Item 文件夹的页面上,我想创建一个指向 Login
方法的链接.那么我应该使用哪个 Html.ActionLink
方法以及我应该传递哪些参数?
On a page that is not located at the Item folder, where ItemController
resides, I want to create a link to the Login
method. So which Html.ActionLink
method I should use and what parameters should I pass?
具体来说,我正在寻找替代方法
Specifically, I am looking for the replacement of the method
Html.ActionLink(article.Title,
new { controller = "Articles", action = "Details",
id = article.ArticleID })
在最近的 ASP.NET MVC 版本中已被淘汰.
that has been retired in the recent ASP.NET MVC incarnation.
推荐答案
我想你想要的是这个:
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签名:
This uses the following method ActionLink signature:
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string controllerName,
string actionName,
object values,
object htmlAttributes)
ASP.NET MVC2
两个参数已经切换
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).
)
这里使用以下方法ActionLink签名:
This uses the following method ActionLink signature:
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
ASP.NET MVC3+
参数与 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).
)
这避免了将任何路由逻辑硬编码到链接中.
This avoids hard-coding any routing logic into the link.
<a href="/Item/Login/5">Title</a>
这将为您提供以下 html 输出,假设:
This will give you the following html output, assuming:
article.Title = "标题"
article.ArticleID = 5
- 您仍然定义了以下路线
..
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
这篇关于HTML.ActionLink 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!