当前位置:首页 > Web开发 > 正文

细说@Html.ActionLink()的用法

2024-03-31 Web开发

https://www.cnblogs.com/sunshineground/p/4360469.html

一、@Html.ActionLink()概述

  在MVC的Rasor视图引擎中,微软给与一种全新的方法来暗示畴前的超链接方法,它取代了畴前的繁杂的超链接标签,让代码看起来越发简洁。通过浏览器依然会解析成传统的a标签。除此之外,还允许我们添加Html属性。下面来看看@Html.ActionLink()的使用要领吧。

二、@Html.ActionLink()的使用详解

  1. @Html.ActionLink("linkText", "actionName")

  这种重载的第一个参数是该链接要显示的文字,第二个参数是对应的控制器的要领(Action),默认控制器为当前页面对应的控制器。

  例如,当前页面的控制器为ProductsController:@Html.ActionLink("detial", "Detial")会生成<a href="http://www.mamicode.com/Products/Detail">detail</a>

  2. @Html.ActionLink("linkText", "actionName", "controllerName")

  该重载比第一个重载多了一个参数,,他指定了控制器的名称。

  例如,@Html.ActionLink("detail", "Detail", "Products")会生成<a href="http://www.mamicode.com/Products/Detail">detail</a>

  3. @Html.ActionLink("linkText", "actionName", routeValues)

  相对付上一种重载,该重载新增了routeValue参数,routeValue可以向action通报参数。

  例如,@Html.ActionLink("detail", "Detail", new{ id = 1 })会生成<a href="http://www.mamicode.com/Products/Detail/1">detail</a>

  4. @Html.ActionLink("linkText", "actionName", routeValues, htmlAttributes)

  htmlAttribute可以设置<a>标签的属性。

  例如,@Html.ActionLink("detail", "Detail", new{ id = 1 }, new{ target = "_blank" })会生成<a href="http://www.mamicode.com/Products/Detail/1" target="_blank">detail</a>,需要注意的是如果写成new{ target="_blank", }则会报错,因为Class是C#的关键字,此时应该写成@class="className"。

  5. @Html.ActionLink("linkText", "actionName", "controllerName", routeValues, htmlAttributes)

  该种重载汇聚了以上此种重载的所有参数,是成果最全的重载。

三、@Url.Action(),@Html.ActionLink(),Html.RenderAction()和@Html.Action()的区别

1. 返回值差别

@Html.Action()返回值为MvcHtmlString。Html.Action对照灵活,可以直接写在页面上,也可以把它赋值给某一变量,措置惩罚惩罚之后写在页面上。

Html.RenderAction()返回值为void。Html.RenderAction必需写在@{}内,直接由Response东西输出。例:@{ Html.RenderAction("Index", "Import");}

@Html.ActionLink()返回值也是MvcHtmlString。

@Url.Action()返回值为string。MvcHtmlString素质上也是string,两者都可以直接此刻页面上。

2. 生成的对象差别

@Html.ActionLink("myLink", "CCC", "Import")生成<a href="http://www.mamicode.com/Import/CCC">myLink</a>

@Url.Action("CCC", "Import")直接生成字符串"http://www.mamicode.com/Import/CCC",没有任何tag标签。

细说@Html.ActionLink()的用法

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30310.html