Asp.Net Core Razor页面
Razor页面应用是MVC框架的一种简化应用,与传统Web开发模式相似,以页面为单位来划分应用功能。
自定义Razor页面的根目录
Razor页面在项目中的默认存储路径是/Pages目录,即所有页面必须放在该目录下。而请求的URL中是不包含根目录名字的,例如某个页面文件路径为 /Pages/News/List.cshtml ,那么请求该页面的URL应为 http://<域名/端口>/News/List。
如果不想将Razor页面放到/Pages目录下,可通过RazorPagesOptions
选项类的RootDirectory
属性来配置自定义页面存放路径,也可用扩展方法简单配置。
public class Startup { public void ConfigureServices(IServiceCollection services) { //services.AddMvc(); //services.PostConfigure<RazorPagesOptions>(option=> //{ // option.RootDirectory = "/CustPages"; //}); services.AddMvc().WithRazorPagesRoot("/CustPages"); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } }
Razor页面与页面模型关联
Razor代码文件只要在文档首行加上@page指令,并且将页面放在程序所配置的根目录下,就可以在URL中访问了。
如果页面涉及相对复杂的业务逻辑处理,就需要创建一个页面模型类来编写独立的处理代码,使得视图与代码分离。页面模型类需要从PageModel
类派生。通过声明约定的方法与视图逻辑交互,通过名为handler
的路由参数来调用这些方法。
一般命名规则为:On<HTTP method><handler name>[Async]
。
- 方法以“On”开头。
- 紧接着是HTTP-method,如GET、POST、DELETE等。
- 然后是“正式名称”,此名称可直接作为路由参数handler的值。
- 如果是异步方法,可用Async结尾。
例如,OnGet,OnGetStudentInfos,OnPostFileAsync等。
页面模型类还可公开属性,便于视图代码绑定。由于HTTP往返通信是无状态的,此过程中属性值通常会丢失,希望保留的话可在属性上加BindPropertyAttribute
特性。
在Razor页面上通过@model指令让视图与页面模型类关联起来,如@model TestModel
。
项目模板在添加新Razor页面时,一般会生产一个与页面名字相同的页面模型类。如,添加一个Test.cshtml的页面,就会生成一个Test.cshtml.cs类,是从PageModel类派生的。
public class TestModel : PageModel { #region 属性 [BindProperty] public string ProductName { get; set; } [BindProperty] public DateTime ProductDate { get; set; } [BindProperty] public Guid ProductID { get; set; } [BindProperty] public string ProductFamily { get; set; } #endregion public void OnGet() { ProductID = Guid.NewGuid(); ProductName = "<未知产品>"; ProductDate = DateTime.Today; ProductFamily = "<未知分类>"; } public void OnPost() { ViewData["msg"] = "恭喜你,提交成功"; } }
@page @using Demo @model TestModel @addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>测试页面</title> </head> <body> <form method="post"> 产品编号:<input type="text" readonly asp-for="ProductID"/><br/> 产品名称:<input type="text" asp-for="ProductName"/><br/> 生产日期:<input type="text" asp-for="ProductDate"/><br/> 产品分类:<input asp-for="ProductFamily"/><br/> <br/><br/> <input type="submit" value="提交"/> </form> <div> @{ if (ViewData.ContainsKey("msg")) { <p>@ViewData["msg"].ToString()</p> } } </div> </body> </html>
Razor Page应用的路由映射
当Razor Page项目的URL路径较长的时候,可以使用路由映射来缩短。
- 如下在方法中注册与MVC相关的服务,并且添加路由映射配置。
public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddRazorPagesOptions(o => { o.Conventions .AddPageRoute("/Start", "/") .AddPageRoute("/Users/NewUser", "/regnew") .AddPageRoute("/Users/UserList", "/showlist"); }); }
AddPageRoute
方法的第一个参数是真实页面地址,第二个参数是路由之后的新地址。如果将路由映射为“/”或者空字符串,就可以使该页面变成主页。
通过@page指令设置Razor页面的URL路由
在@page指令之后,可以使用字符串实例来指定路由映射。
(1)直接指定路径段,表示该路由是相对于当前页面的。例如,指定字符串“renew”,当前页面是Orders,那么最终访问的URL为 http://demo.net/orders/renew 。
(2)如果指定的字符是以“/”或者“~/”开头,则表示其路由是相对于根URL的。例如,页面/users/admin,而指定的路由为“/admin”,那么访问的URL为 http://demo.net/admin 。
- 例
Pages目录下添加一个 Main.cshtml。
@page "/" <html> <body> <h2>主页</h2> <div> <a href="/musics">我的音乐</a> <a href="/photos">我的照片</a> </div> </body> </html>
Pages目录下添加一个Funcs目录,Funcs下添加 MyMusics.cshtml 和 MyPhotos.cshtml。
@page "/musics" <html> <body> <h2>我的音乐</h2> </body> </html>
@page "/photos" <html> <body> <h2>我的照片</h2> </body> </html>
自定义页面的handler方法
在页面模型中,OnGet、OnPost等方法会根据页面的请求方法自动被调用。
但是这些约定的方法有时不能满足开发需求,因此框架允许自定义这些方法的名称,在路由数据字典中,这些页面方法被命名为handler。默认情况下时通过URL的请求参数来调用页面方法的,例如,http://localhost/students?handler=UploadPic ,其中students是页面名,UploadPic是方法名,实际方法命名应为OnGetUploadPic。
如果不希望URL中出现handler字段,可通过@page指令来自定义路由,例如,@page "{handler?}"
,handler是路由字典参数,必须写在一对大括号中,后面的问号表示该值为可选。URL可变为 http://localhost/students/UploadPic 。
在实际使用时,可以使用扩展标记帮助器在运行时自动生成URL,例如,asp-page标记属性指定要执行的页面,当前页面可以忽略,asp-page-handler
标记属性指定要执行的handler的名称。
- 例
@page "{handler?}" @addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers @model Demo.TestModel <html> <body> <form method="post"> 用户名: <input type="text" name="username" /><br /> 密码: <input type="password" name="password"/><br/> <div> <input type="submit" value="公开登录" asp-page-handler="LoginPublic"/> <input type="submit" value="隐身登录" asp-page-handler="LoginHidden"/> </div> </form> </body> </html>
test页面在两个提交按钮上,通过asp-page-handler标记属性来指定要调用的方法,由于处理的方法将在当前页面的模型类中定义,所以不需要asp-page标记。
public class TestModel : PageModel { public ActionResult OnPostLoginPublic(string username, string password) { string msg = $"你以公共方式登录,输入的用户名为{username},密码为{password}"; return Content(msg); } public ActionResult OnPostLoginHidden(string username, string password) { string msg = $"你以隐身方式登录,输入的用户名为{username},密码为{password}"; return Content(msg); } }
本文来自博客园,作者:一纸年华,转载请注明原文链接:https://www.cnblogs.com/nullcodeworld/p/18210634
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)