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

相关内容

热门资讯

透视解谜!德普之星辅助器app... 透视解谜!德普之星辅助器app(透视)拱趴大菠萝开挂方法,教程技法(证实有挂)-哔哩哔哩1)拱趴大菠...
透视解迷!pokerrrr2辅... 透视解迷!pokerrrr2辅助(透视)哈糖大菠萝攻略,教程方案(有挂秘诀)-哔哩哔哩1、哈糖大菠萝...
透视解谜!WePoKer辅助器... 透视解谜!WePoKer辅助器(透视)wepoker私人局俱乐部辅助,教程积累(有挂规律)-哔哩哔哩...
透视开挂!sohoo竞技联盟辅... 透视开挂!sohoo竞技联盟辅助器(透视)德州局透视脚本免费版下载手机版,教程妙计(有挂神器)-哔哩...
透视揭幕!aapoker能控制... 透视揭幕!aapoker能控制牌吗(透视)epoker底牌透视,教程资料(确实有挂)-哔哩哔哩1、玩...
透视分享!wepoker有辅助... 您好,wepoker有辅助器吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
透视推荐!wepoker软件辅... 透视推荐!wepoker软件辅助程序(透视)wepoker软件辅助程序,教程烘培(有挂解密)-哔哩哔...
透视科普!hhpoker是正规... 透视科普!hhpoker是正规的吗(透视)hhpoker辅助器视频,教程窍要(详细教程)-哔哩哔哩1...
透视解密!xpoker辅助助手... 透视解密!xpoker辅助助手(透视)hhpoker德州挂真的有吗,教程手筋(真的有挂)-哔哩哔哩;...
透视科普!we poker游戏... 透视科普!we poker游戏下(透视)poker world辅助器,教程法子(有挂规律)-哔哩哔哩...