接着上篇,本篇開始講下實現登錄窗口,先看下大概的效果圖:

打開的效果,沒有美工美化

點登錄校驗得到不能為空
我在做blazor時用到了一個ui框架,這個框架名叫Ant Design blazor(https://gitee.com/ant-design-blazor/ant-design-blazor),安裝步驟如下:
1、打開項目里的Nuget,查找 AntDesign ,找到后安裝
2、在項目中(Program.cs)注冊:
services.AddAntDesign();
3、在 wwwroot/index.html(WebAssembly) 或 Pages/_Host.razor(Server) 中引入靜態文件:
<link href="_content/AntDesign/css/ant-design-blazor.css" rel="stylesheet" /> <script src="_content/AntDesign/js/ant-design-blazor.js"></script>
4、在 _Imports.razor 中加入命名空間
@using AntDesign
5、為了動態地顯示彈出組件,需要在 App.razor 中添加一個 <AntContainer /> 組件。
<Router AppAssembly="@typeof(MainLayout).Assembly"> <Found Context="routeData"> <RouteView RouteData="routeData" DefaultLayout="@typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <Result Status="404" /> </LayoutView> </NotFound> </Router> <AntContainer /> <-- 在這里添加
以上安裝完成AntDesign Blazor了就。然后就可以使用他的組件了。
先看下Login.Razor的代碼
@page "/login" @layout LoginLayout @using System.ComponentModel.DataAnnotations; @using System.Text.Json; @inject TokenHttpClient TokenHttp <Form Model="@model" LabelCol="new ColLayoutParam { Span = 8 }" WrapperCol="new ColLayoutParam { Span = 16 }" OnFinish="OnFinish" OnFinishFailed="OnFinishFailed"> <FormItem Label="用戶名"> <Input @bind-Value="@context.Username" /> </FormItem> <FormItem Label="密 碼"> <InputPassword @bind-Value="@context.Password" /> </FormItem> <FormItem WrapperCol="new ColLayoutParam{ Offset = 8, Span = 16 }"> <Checkbox @bind-Value="context.RememberMe">Remember me</Checkbox> </FormItem> <FormItem WrapperCol="new ColLayoutParam{ Offset = 8, Span = 16 }"> <Button Type="@ButtonType.Primary" HtmlType="submit"> 登錄 </Button> </FormItem> </Form> @code { public class UserLoginDto { [Required(ErrorMessage ="用戶名不能為空")] public string Username { get; set; } [Required(ErrorMessage = "密碼不能為空")] public string Password { get; set; } public bool RememberMe { get; set; } = false; } private UserLoginDto model = new UserLoginDto(); private void OnFinish(EditContext editContext) { HttpResponseMessage message = TokenHttp.PostAsJsonAsync(TokenHttpClient.RequesUrl + "", model).Result; //Todo } private void OnFinishFailed(EditContext editContext) { //Todo } }
代碼我們主要關注幾個地方:
1、Login.Razor用了自己獨立的Layout,叫LoginLayout,它的代碼如下:
@inherits LayoutComponentBase <Layout> <Content Style="overflow: auto; height: 100vh; width:100vw; position: fixed; left: 0; background:#808080 "> <div style="margin:40vh auto auto 40vw;width:20vw;"> @Body </div> </Content> </Layout>
LoginLayout實現了一個用css控制登錄框居中的效果。
2、TokenHttpClient 類,本來用HttpClient也是能實現與后台交互的,但是由於我在項目用到了一個token需要在一定條件下刷新的功能,就做了個繼承自HttpClient的類TokenHttpClient,如果沒有這種特殊需求,這塊可以不用,可以直接用HttpClient。用了這個類那么在Program.cs里就要添加
builder.Services.AddTransient<TokenHttpClient>();
3、重點請看UserLoginDto,這是數據傳輸對象,這里用到的數據校驗方式是否似曾相識,沒錯,后台開發時經常用到這種驗證的方法。這里在blazor里可以直接這樣用。效果就是上邊截圖顯示的那種效果。是不是很優雅。比js那種亂七八糟的舒服多了吧。
4、往后台交互提交數據是在OnFinish里,數據通過HttpClient直接可以往后台提交。(不是Ajax哦)
以上就是本篇實現的東西,由於后台采用的Abp vnext 框架,目前登錄后台功能還沒實現好,所以這塊還沒完成,等完成了發布新的給大家看。