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);
}

相关内容

热门资讯

玩家亲测!wpk有作弊吗,有哪... 玩家亲测!wpk有作弊吗,有哪些免费的wpk作弊码,竟然是真的有挂(有挂实锤)1. 选牌创建新账号,...
一秒答解!hhpoker怎么开... 一秒答解!hhpoker怎么开透视,wepoker脚本,总是有挂(有挂头条)1、完成有辅助插件,帮助...
推荐一款!wepoker辅助透... 推荐一款!wepoker辅助透视软件,wepoker公共底牌,总是真的有挂(有挂秘笈)进入游戏-大厅...
最新技巧!wpk是真的还是假的... 最新技巧!wpk是真的还是假的,pokemmo脚本最新版,竟然存在有挂(详细教程)1、让任何用户在无...
一起来探讨!wepoker怎么... 一起来探讨!wepoker怎么发冤家牌,aapoker怎么设置抽水,一直存在有挂(有挂攻略)1)有没...
热点推荐!拱趴大菠萝挂哪里,红... 热点推荐!拱趴大菠萝挂哪里,红龙poker作弊指令,一贯是真的有挂(有挂工具)1、拱趴大菠萝挂有没有...
揭秘攻略!hhpoker有透视... 揭秘攻略!hhpoker有透视功能吗,pokemmo脚本辅助器,原来是有挂(有挂方法);该软件可以轻...
玩家必备教程!如何下载wepo... 玩家必备教程!如何下载wepoker安装包,pokemmo辅助器脚本下载,本来是有挂(有挂透视)玩家...
科技揭秘!德州局HHpoker... 科技揭秘!德州局HHpoker透视脚本,哈糖大菠萝怎么挂,都是真的是有挂(有挂存在)1、免费辅助多个...
推荐一款!wepoker透视脚... 推荐一款!wepoker透视脚本安卓,hh poker软件,都是真的有挂(确实有挂)1、脚本辅助下载...