<strong>一. 在视图中生成输入URL</strong>
如一个静态的a元素:
<a href="/Home/CustomVariable">This is an outgoing URL</a>
手工硬编码URL的方法乏味和易错。
<strong>1.1 用路由系统生成输入URL</strong>
初始时:RouteConfig中的路由为:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
在View中生成输出URL最简单的方法:在View中使用Html.ActionLink方法。
<div>
@Html.ActionLink("This is an outgoing URL", "CustomVariable")
</div>
效果虽然和手动写链接一样,但是,加入现在新加了路由定义:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
routes.MapRoute("NewRoute", "App/Do{action}",
new { controller = "Home" });
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
此时ActionLink所生成的HTMl为:
<a href="/App/DoCustomVariable">This is an outgoing URL</a>
即:改变定义URL方案的路由,会改变输出URL的生成方式。
<strong>1.2 以其它Controller为目标生成输入URL</strong>
<div>
@Html.ActionLink("This is an outgoing URL", "Index", "Admin");
</div>
生成的URL为
http://localhost:24903/Admin
<strong>1.3 传递额外的值</strong>
可以通过匿名类给一些片段传递值,匿名类中以属性表示片段。
@Html.ActionLink("This is an outgoing URL", "CustomVariable", new { id = "Hello" })
得到:
http://localhost:24903/Admin/CustomVariable/Hello
<strong>1.4 指定HTML标签属性</strong>
通过一个匿名类,可以给a元素设置属性:
<div>
@Html.ActionLink("This is an outgoing URL", "Index", "Home", null, new { id = "myAnchorID", @class = "myCssClass" })
</div>
这个匿名类具有id和class属性,@class表示使用关键字作为class成员的名字。
得到的HTML为:
<a class="myCssClass" href="/App/DoIndex" id="myAnchorID">This is an outgoing URL</a>
<strong>1.5 生成链接中的全限定URL</strong>
@Html.ActionLink("This is an outgoing URl", "Index", "Home",
"https", "myserver.mydomain.com", " myFragmentname", new { id = "MyId" },
new { id = "myAnchorID", @class = "myCssClass" })
生成的HTML为:
<a class="myCssClass" href="https://myserver.mydomain.com/App/DoIndex?id=MyId# myFragmentname" id="myAnchorID">This is an outgoing URl</a>
<strong>1.6 生成URL,而不是链接</strong>
可以使用Url.Action方法只生成URL而不生成HTML:
<div>
this is a URL:
@Url.Action("Index", "Home", new { id = "myId" })
</div>
生成了URL:
this is a URL: /Home/Index/myId
<strong>1.7 在Action中生成输入URL</strong>
public ViewResult MyActionMethod()
{
string myActionUrl = Url.Action("Index", new { id = "MyID" });
string myRouteUrl = Url.RouteUrl(new { controller = "Home", action = "Index" });
return View();
}
更普遍的需求是,把浏览器重定向到另一个URL:
public RedirectToRouteResult MyActionMethod()
{
return RedirectToAction("Index");
}
或者
public RedirectToRouteResult MyActionMethod()
{
return RedirectToRoute(new { controller = "Home", action = "Index", id = "MyID" });
}
<strong>二. 使用区域</strong>
网友评论