AspNetMVC的ModelState验证不起作用
创始人
2024-09-20 09:31:27
0

首先,在您的控制器中确保您使用ModelState.IsValid进行验证。比较常见的错误之一是使用HttpContext.Current而不是ModelState.IsValid来验证。具体代码示例如下:

[HttpPost]
public ActionResult Create(Student student)
{
    if (ModelState.IsValid)
    {
        db.Students.Add(student);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(student);
}

如果您的控制器存在嵌套属性的复杂模型,则需要手动调用验证器,以确保属性级别的验证器在模型的层次结构中正确触发。例如:

[HttpPost]
public ActionResult Create(Course course)
{
    ValidateCourse(course);

    if (ModelState.IsValid)
    {
        db.Courses.Add(course);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(course);
}

private void ValidateCourse(Course course)
{
    if (course.InstructorID == null)
    {
        ModelState.AddModelError("InstructorID", "The instructor field is required.");
    }
    ...
}

您还可以检查自定义的模型验证器进行排除。确保您的验证器正确设置错误消息并将其添加到模型状态中,如下所示:

public class StudentMetadata
{
    [Required(ErrorMessage = "The first name field is required.")]
    public string FirstName { get; set; }

    [StringLength(50, MinimumLength = 2, ErrorMessage = "The last name must be between 2 and 50 characters.")]
    public string LastName { get; set; }
}

[MetadataType(typeof(StudentMetadata))]
public partial class Student
{
    // Here you can add custom validation rules for Student
    // e.g. [Compare("Email", ErrorMessage = "The email and confirm email must match.")]
}

[HttpPost]
public ActionResult Create(Student student)
{
    if (ModelState.IsValid)
    {
        db.Students.Add(student);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(student);
}

相关内容

热门资讯

第3分钟辅助!德普之星透视辅助... 第3分钟辅助!德普之星透视辅助软件,德普之星怎么开辅助,步骤教程(详细教程)1、金币登录送、破产送、...
七分钟辅助!aapoker公共... 七分钟辅助!aapoker公共底牌,hhpoker作弊码,机巧教程(有挂规律)1.aapoker公共...
8分钟辅助!wepoker免费... 8分钟辅助!wepoker免费钻石,德扑圈透视挂,妙招教程(有挂方式)1、金币登录送、破产送、升级送...
八分钟辅助!wepoker怎么... 八分钟辅助!wepoker怎么看底牌,wepoker辅助是真的假的,攻略教程(有挂详细)1、实时we...
9分钟辅助!wepoker有脚... 9分钟辅助!wepoker有脚本吗,德普之星辅助工具如何设置,教程书教程(有挂透明挂)1、实时德普之...
第1分钟辅助!hhpkoer辅... 第1分钟辅助!hhpkoer辅助挂是真的吗,wepoker辅助器免费,法子教程(有挂总结)一、hhp...
第1分钟辅助!wpk透视工作室... 第1分钟辅助!wpk透视工作室,hhpoker辅助软件下载,指南书教程(有挂方法)1)hhpoker...
3分钟辅助!wepoker脚本... 3分钟辅助!wepoker脚本,sohoo开挂辅助,演示教程(有挂分享)1、点击下载安装,sohoo...
第9分钟辅助!wepoker有... 第9分钟辅助!wepoker有辅助插件吗,wpk透视辅助靠谱吗,学习教程(有挂教程)1、任何wepo...
一分钟辅助!拱趴大菠萝挂,hh... 一分钟辅助!拱趴大菠萝挂,hhpoker开挂教程,教程书教程(讲解有挂)1、hhpoker开挂教程辅...