> 文章列表 > .Net MVC中 视图如何使用路由!!!

.Net MVC中 视图如何使用路由!!!

.Net MVC中 视图如何使用路由!!!

配置路由

app.UseEndpoints(endpoints =>

{

    endpoints.MapControllerRoute(

        name: "default",

        pattern: "{controller=Home}/{action=Index}/{id?}");

});

在视图中使用路由

 页面跳转常用的路由设置

标签属性

描述

asp-action

指定控制器的action方法

asp-controller

指定控制器

asp-route-xxx

指定xxx片段值

asp-protocol

指定协议 (例如: https)

asp-host

指定服务器名称 (例如:baidu.com)

asp-fragment

指定锚点

asp-route-area

指定区域片段变量的值

完全约束住的URL

<a asp-action="Index" asp-controller="Home" asp-route-id="Hello"

    asp-protocol="https" asp-host="myserver.mydomain.com" asp-fragment="myFragment">

    完全约束住的URL

</a>

 

html源码显示:

<a href="https://myserver.mydomain.com/Home/Index/Hello#myFragment">

忽略片段

@*路由系统知道应用程序中的路由默认使用Index方法,所以生成的Html忽略了不必要的片段变量*@

<a asp-action="Index" asp-controller="Admin">跳转过Admin控制器的Index方法</a>

 

html源码显示:

<a href="/Admin">跳转过Admin控制器的Index方法</a>

定位操作方法

@*因为在控制器中使用了Route特性*@

<a asp-action="Index" asp-controller="Customer">跳转过Customer控制器的Index方法</a>

 

html源码显示:

<a href="/app/Customer/actions/Index">跳转过Customer控制器的Index方法</a>

 

为什么会这样?因为控制器使用了Route特性:

[Route("app/[controller]/actions/[action]/{id:weekday?}")]

public class CustomerController : Controller

{

}

非链接的URL:标签助手

<p>URL:@Url.Action("CustomVariable","Home",new{id=100})</p>

 

html源码显示:

<p>URL:/home/customvariable/100/</p>

命名路由

Startup配置路由:

endpoints.MapControllerRoute(

    name: "out",

    pattern: "outbound/{controller=Home}/{action=Index}");

 

视图使用:

<a asp-route="out">匹配路由列表中nameout的路由</a>

 

html源码显示:

<a href="/outbound">匹配路由列表中name为out的路由</a>