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

相关内容

热门资讯

透视免费!hhpoker可以开... 透视免费!hhpoker可以开挂吗,微信小程序微乐安徽辅助苹果,了解脚本(存在有挂)-哔哩哔哩进入游...
网友热议!德普之星辅助软件,微... 网友热议!德普之星辅助软件,微信小程序微乐房间透视,科普透视(有挂规律)-哔哩哔哩德普之星辅助软件是...
透视新版!hardrock透视... 透视新版!hardrock透视工具,微信小程序微乐房间有挂吗,科普脚本(有挂方法)-哔哩哔哩1、ha...
脚本关于!hhpoker有辅助... 脚本关于!hhpoker有辅助吗,hhpoker智能辅助插件(透视)竟然是真的工具(哔哩哔哩)1、实...
透视了解!德普之星透视辅助软件... 透视了解!德普之星透视辅助软件是真的吗,微乐广西小程序插件,总结脚本(有挂教程)-哔哩哔哩1、首先打...
透视总结!wpk辅助器是真的吗... 透视总结!wpk辅助器是真的吗,wpk私人局辅助是真的吗(透视)竟然真的有技巧(哔哩哔哩)1、下载好...
透视讲解!pokermaste... 透视讲解!pokermaster修改器,微信小程序微乐辅助,教你脚本(有挂技术)-哔哩哔哩1、每一步...
值得注意的是!aapoker透... 值得注意的是!aapoker透视脚本下载,小程序微乐陕西挖坑辅助,解密透视(有挂解惑)-哔哩哔哩一、...
脚本必备!wpk俱乐部辅助器,... 脚本必备!wpk俱乐部辅助器,wpk私人辅助(透视)确实存在有教程(哔哩哔哩)1、很好的工具软件,可...
透视辅助!wpk软件是正规的吗... 透视辅助!wpk软件是正规的吗,在哪里下载微乐自建房辅助软件,分享脚本(发现有挂)-哔哩哔哩一、wp...