asp.net core模型绑定和模型验证

模型绑定以及模型验证

模型绑定

Demo:添加学生信息

1、在Controller中创建Create方法

				[HttpGet]
				public IActionResult Create()
        {
            return View();
        }
        
        [HttpPost]
        public IActionResult Create(Student student)
        {
           return RedirectToAction("Details", new {id = newStudent.Id}); 
        }

2、创建对应的View视图

@model Student
@{
    ViewBag.Title = "创建学生信息";
}
<form asp-controller="home"
      asp-action="create"
      method="post"
      class="mt-3">
    <div class="form-group row">
        <div class="col-sm-10">
            <input asp-for="Name" class="form-control" placeholder="请输入名字"/>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-10">
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="ClassName" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <select asp-for="ClassName"
                    asp-items="Html.GetEnumSelectList<ClassNameEnum>()"
                    class="custom-select mr-sm-2">
            </select>
        </div>
    </div>
    <div class="col-sm-10">
        <button type="submit" class="btn-primary">创建</button>
    </div>
</form>

要将HTTP的请求数据绑定到控制器操作方法上对应的参数上,模型绑定将按以下顺序在以下位置查找来自HTTP请求的数据。

Form values:表单中值

Route values:路由中的值

Query strings:查询字符串

模型验证

Demo:添加学生信息验证

第一步,在对应的Model层添加Required等

public class Student
    {
        public int Id { get; set; }
        
        [Display(Name = "姓名"),MaxLength(50,ErrorMessage = "名字的长度不能超过50个字符")]
        [Required(ErrorMessage = "请输入名字")]
        public string Name { get; set; }
        public ClassNameEnum ClassName { get; set; }
        
        [Required(ErrorMessage = "请输入邮箱地址")]
        [RegularExpression(
                @"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$"
                ,ErrorMessage = "邮箱格式不正确")]
        [Display(Name = "邮箱地址")]
        public string Email { get; set; }
    }

第二步,在控制器中添加ModelSate.IsValed验证,并对控制器进行改造

public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            { 
                Student newStudent = _studentRepository.Add(student);
                return View("Details", new { id = newStudent.Id} );
                
//                return RedirectToAction("Details", new {id = newStudent.Id}); 

            }

            return View();
        }

第三步,在视图文件中添加TagHelper用于表现层的验证和提示

@model Student
@{
    ViewBag.Title = "创建学生信息";
}
<form asp-controller="home"
      asp-action="create"
      method="post"
      class="mt-3">
    
    @* asp-validation-summary="All”:验证所有属性 *@
    <div class="text-danger" asp-validation-summary="All"></div>


    <div class="form-group row">
       @* asp-for用于对验证属性进行绑定 *@
        <label asp-for="Name" class="col-sm-2 col-form-label"></label>
        
        <div class="col-sm-10">
            <input asp-for="Name" class="form-control" placeholder="请输入名字"/>
          @* asp-validation-for="Name"用于验证后的结果显示 *@
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        
    </div>
    <div class="form-group row">
        <label asp-for="Email" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Email" class="form-control" placeholder="请输入邮箱"/>
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>



    <div class="form-group row">
        <label asp-for="ClassName" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
          @* asp-ietms对枚举类进行遍历 *@
            <select asp-for="ClassName"
                    asp-items="Html.GetEnumSelectList<ClassNameEnum>()"
                    class="custom-select mr-sm-2">
            </select>
        </div>
    </div>

    <div class="col-sm-10">
        <button type="submit" class="btn-primary">创建</button>
    </div>
</form>

附加:ClassNameEnum枚举类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Models
{
    public enum ClassNameEnum
    {
        [Display(Name = "未选择")]
        None,
        [Display(Name = "一年级")]
        FirstGradel,
        [Display(Name = "二年级")]
        SecondGradel,
        [Display(Name = "三年级")]
        GradeThree 
    }
}

Select标签验证:

第一步:修改Model层

Students.cs

public class Student
    {
				// ?表示可空
        [Required]
        public ClassNameEnum? ClassName { get; set; }
        
    }

第二部,在View层中的Select标签中添加一个可空的option标签

<select asp-for="ClassName"
                    asp-items="Html.GetEnumSelectList<ClassNameEnum>()"
                    class="custom-select mr-sm-2">
                <option value="请选择"></option>
            </select>

第三部,修改之前的BUG

由于Detail的View可传入的对象为一个Model,所以需要将Controller里面的View方法改为RedirectToAction方法

HomeController.cs

public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            { 
                Student newStudent = _studentRepository.Add(student);
//                return View("Details", new { id = newStudent.Id} );
                return RedirectToAction("Details", new {id = newStudent.Id});
            }
            return View();
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值