1. 程式人生 > >ASP.NET Core使用Razor頁面

ASP.NET Core使用Razor頁面

.json clas ldm ice post nbu www type bind

ASP.NET Core使用Razor頁面

Razor是ASP.NET的頁面引擎,在ASP.NET MVC 3以後被廣泛使用,我在之前的博客中有所介紹,需要更多了解的朋友請移步【Razor語法】

在ASP.NET中,我們仍然使用Razor來構建Web頁面。

首先使用Visual Studio 2017創建一個Web應用程序,打開創建好的項目,可以看到VS已經為我們創建好了項目的結構:

文件/文件夾 說明
wwwroot 靜態文件目錄
Pages Razor頁面
appsettings.json 配置
Program.cs 托管ASP.NET Core的應用
Startup.cs 應用啟動類,用於配置應用程序

與空白應用程序不同的是,Web應用默認為我們引用了MVC管道,代碼在Startup文件中:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseMvc();
}

接下來我們創建一個自己的Razor頁面。

Hello World 頁面

在Razor文件夾郵件,選擇Razor,不使用模板頁,創建好以後,可以看到生成了兩個文件:

文件名 說明
HelloWorld.cshtml Razor頁面
HelloWorld.cshtml.cs Razor頁面對應的Model

如果需要修改HTML代碼,則在Razor頁面中進行修改;數據、頁面行為等內容則在Model文件中進行修改。

運行我們的HelloWorld頁面,Razor對應的頁面地址為:~/HelloWorld

添加Model字段

為了測試Model的用法,我們在Model中添加兩個字段,並在OnGet方法中賦值,修改後的Model如下:

public class HelloWorldModel : PageModel
{
    /// <summary>
    /// 操作
    /// </summary>
    public string Method { get; set; }

    /// <summary>
    /// 服務器時間
    /// </summary>
    public string ServerTime
    {
        get
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }

    public void OnGet()
    {
        this.Method = "Get";
    }
}

對頁面進行修改,添加顯示Model中字段的代碼:

<body>
    <h1>Hello World</h1>
    <p>
        Method:@Model.Method
    </p>
    <p>
        Server time:@Model.ServerTime
    </p>
</body>

編譯應用程序,刷新瀏覽器中的頁面查看效果。

添加POST操作

添加新的實體Visitor

public class Visitor
{
    public string Name { get; set; }
    public string Email { get; set; }
}

在Model中添加OnPost代碼:

/// <summary>
/// 訪客
/// </summary>
[BindProperty]
public Visitor Visitor { get; set; }

/// <summary>
/// Post操作
/// </summary>
public void OnPost(Visitor visitor)
{
    this.Method = "Post";
    this.Visitor = visitor;
}

對Visitor字段使用了BindProperty特性,表明這個字段進行綁定操作。

對頁面進行修改:

<form method="post">
    <p>
        <label>姓名:</label>
        <input type="text" asp-for="Visitor.Name" />
    </p>
    <p>
        <label>郵箱:</label>
        <input type="text" asp-for="Visitor.Email" />
    </p>
    <input type="submit" value="提交" />
</form>

刷新頁面,填寫相應的信息,隨後點擊提交按鈕,OnPost方法可以正常接收到參數,更新後的頁面也可以帶出剛才提交的數據。

添加數據驗證

public class Visitor
{
    [Required]
    [StringLength(20, MinimumLength =5)]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }
}

使用DataAnnotations對Visitor類中的字段進行標註。然後在OnPost中進行驗證:

/// <summary>
/// Post操作
/// </summary>
public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Redirect("~/HelloWorld");
    }

    this.Method = "Post";
    return Page();
}

此時,如果提交的數據不能通過驗證,則頁面跳轉到Get請求。

ASP.NET Core使用Razor頁面