假设我有一门课
public class ItemController:Controller
{
public ActionResult Login(int id)
{
return View("Hi", id);
}
}在一个不在ItemController所在的Item文件夹中的页面上,我想创建一个指向Login方法的链接。那么,我应该使用哪个Html.ActionLink方法,应该传递什么参数呢?
具体地说,我正在寻找方法的替换
Html.ActionLink(article.Title,
new { controller = "Articles", action = "Details",
id = article.ArticleID })在最近的ASP.NET MVC化身中已经停用了。
发布于 2008-10-14 14:19:34
我想你想要的是:
ASP.NET MVC1
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)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签名方法如下:
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).
)这避免了将任何路由逻辑硬编码到链路中。
<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
);发布于 2009-03-09 11:57:53
我想添加到Joseph Kingry's answer中。他提供了解决方案,但一开始我也不能让它工作,得到的结果就像Adhip Gupta一样。然后我意识到路由必须首先存在,参数需要与路由完全匹配。因此,我有一个id,然后是我的路由的一个文本参数,它也需要包括在内。
Html.ActionLink(article.Title, "Login", "Item", new { id = article.ArticleID, title = article.Title }, null)发布于 2008-10-14 15:39:06
您可能希望查看RouteLink() method.That one,它允许您通过字典指定所有内容(链接文本和路由名称除外)。
https://stackoverflow.com/questions/200476
复制相似问题