表单和数据注释验证

这是一个关于使用EditForm和DataAnnotations进行表单验证的Blazor应用示例。用户需输入标题、slug和内容,所有字段均为必填,slug长度限制为16字符。当表单验证通过后,会显示提交的信息。
摘要由CSDN通过智能技术生成
@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; }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值