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透视辅助测试!德州nzt... wpk透视辅助测试!德州nzt软件,(AAPOKeR)其实是有挂(详细透视曝光教程);揭秘教程安装方...
透视模拟器(智星德州菠萝有挂吗... 透视模拟器(智星德州菠萝有挂吗)wpk怎么玩胜率高(详细辅助曝光教程)从前是有挂;小薇(透视辅助)致...
wepoke插件!wpk显示有... WePoker透视辅助工具核心要点解析‌,wepoke插件!wpk显示有,(德州aa扑克)素来是真的...
透视辅助(智星德州菠萝开挂)w... 透视辅助(智星德州菠萝开挂)wepokeapp下载教程(详细辅助新2025版)原来是有挂是一款可以让...
透视脚本(aapoker透明挂... 1、透视脚本(aapoker透明挂)wepoke德扑之星(详细辅助解密教程)固有是有挂;详细教程。2...
wepoke模拟器!微扑克有辅... wepoke模拟器!微扑克有辅助插件吗,(AAPoker)果然真的是有挂(详细辅助必备教程)wepo...
透视软件(wpk透明挂)德州w... 透视软件(wpk透明挂)德州wpk德州有挂吗(详细辅助2025版教程)都是有挂您好,,确实是有挂的,...
wepoke的确有挂!微扑克辅... wepoke的确有挂!微扑克辅助多少钱,(wEpOke)先前是有挂(详细辅助透牌教程);wpk透视辅...
透视免费(aapoker辅助)... 透视免费(aapoker辅助)wepoke挂真的(详细辅助微扑克教程)都是有挂1、许多玩家不知道辅助...
aa扑克辅助!约局互娱辅助,(... aa扑克辅助!约局互娱辅助,(来玩德州)先前有挂(详细透视2025新版);原来确实真的有挂(需添加指...