@page "/editforms"
<h3>Edit Forms and Validation</h3>
<EditForm Model="BlogPostModel" OnValidSubmit="HandleValidSubmit">
@*将数据注释验证信息注入到表单控件*@
<DataAnnotationsValidator/>
<div class="row mt-4">
<label for="title">Title</label>
<InputText id="title" @bind-Value="BlogPostModel.Title" class="form-control"></InputText>
</div>
<div class="row mt-4">
<label for="slug">Slug</label>
<InputText id="slug" @bind-Value="BlogPostModel.Slug" class="form-control"/>
</div>
<div class="row mt-4" >
<InputTextArea @bind-Value="BlogPostModel.Content" class="form-control" rows="10"/>
</div>
<div class="row mt-4">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
@*显示验证错误信息*@
<div class="row mt-4">
<ValidationSummary/>
</div>
</EditForm>
@code {
//BlogPostModel为视图的模型对象
//注意:必须new一个实例,否则无法显示视图
protected BlogPost BlogPostModel { get; set; } = new BlogPost();
protected void HandleValidSubmit()
{//提交且验证成项后,处理表单
Console.WriteLine("valid submit!");
Console.WriteLine("Your title: " + BlogPostModel.Title);
Console.WriteLine("Your slug: " + BlogPostModel.Slug);
Console.WriteLine("Your content: " + BlogPostModel.Content);
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorApp3
{
public class BlogPost
{
[Required(ErrorMessage ="标题不能为空")]
public string Title { get; set; }
[Required]
[StringLength(16,ErrorMessage ="Slug is too long (16 character limit).")]
public string Slug { get; set; }
[Required]
public string Content { get; set; }
}
}