C# 远程验证显示错误消息,但仍允许表单提交并保存在数据库MVC 5中

C# 远程验证显示错误消息,但仍允许表单提交并保存在数据库MVC 5中,c#,asp.net-mvc,validation,model-view-controller,data-annotations,C#,Asp.net Mvc,Validation,Model View Controller,Data Annotations,情况是,学生注册的组合。否。和选择课程始终是唯一的 选择之前保存在数据库中的组合后,预期结果为 第一个预期结果: 将出现错误消息“所选学生已参加本课程” 第二个预期结果: 它将阻止表单提交,直到选择了以前未保存在数据库中的其他组合 当前结果: 第一个预期结果是运行良好: 但是,第二个预期结果不起作用。也就是说,它提交表单并保存以前已保存在数据库中的组合 你能给我一个解决方案,因为我可以得到第二个预期的结果吗 提前谢谢 为了便于阅读,我排除了与姓名、电子邮件和部门相关的所有代码、html和脚本

情况是,学生注册的组合。否。选择课程始终是唯一的

选择之前保存在数据库中的组合后,预期结果为

第一个预期结果:

将出现错误消息“所选学生已参加本课程”

第二个预期结果:

它将阻止表单提交,直到选择了以前未保存在数据库中的其他组合

当前结果:

第一个预期结果是运行良好:

但是,第二个预期结果不起作用。也就是说,它提交表单并保存以前已保存在数据库中的组合

你能给我一个解决方案,因为我可以得到第二个预期的结果吗

提前谢谢

为了便于阅读,我排除了与姓名、电子邮件和部门相关的所有代码、html和脚本

这是我的模型

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;

namespace UniversityApplication.Models
{
public class CourseStudent
{
    [Required]
    [DisplayName("Student Reg. No.")]
    public string CourseStudentRegNo { get; set; }

    [Required]
    [Remote("IsCourseNameExists", "CourseStudents", AdditionalFields = "CourseStudentRegNo", ErrorMessage = "Selected Student has taken this course already.")]
    [DisplayName("Select Course")]
    public string CourseStudentCourse { get; set; }

    [Required]
    [DisplayName("Date")]
    [DataType(DataType.Date)]
    public DateTime CourseStudentRegDate { get; set; }
}
}
这是我的控制器

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using UniversityApplication.Context;
using UniversityApplication.Models;

namespace UniversityApplication.Controllers
{
public class CourseStudentsController : Controller
{
    private ApplicationContext db = new ApplicationContext();

    public ActionResult StudentToCourse()
    {
        GenerateDropDownValue();
        return View();
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult StudentToCourse([Bind(Include = "CourseStudentID,CourseStudentRegNo,CourseStudentName,CourseStudentEmail,CourseStudentDepartmentCode,CourseStudentCourse,CourseStudentRegDate")] CourseStudent courseStudent)
    {
        GenerateDropDownValue();

        if (ModelState.IsValid)
        {
            db.CoursesStudents.Add(courseStudent);
            db.SaveChanges();
            ModelState.Clear();

            return View();
        }
        ModelState.Clear();

        return View();            
    }

private void GenerateDropDownValue()
    {
        List<Student> allRegisteredStudents = new List<Student>();
        List<SelectListItem> students = new List<SelectListItem>();

        List<Course> allCourses = new List<Course>();


        string studentName = "";
        string studentEmail = "";
        string studentDepartment = "";

        using (ApplicationContext db = new ApplicationContext())
        {
            allRegisteredStudents = db.Students.OrderBy(a => a.StudentRegNo).ToList();
        }

        foreach (var student in allRegisteredStudents)
        {
            students.Add(

                new SelectListItem()
                {
                    Value = student.StudentRegNo,
                    Text = student.StudentRegNo
                }
                );
        }

        ViewBag.Students = students;
        ViewBag.CourseCode = new SelectList(allCourses, "CourseCode", "CourseName");
        ViewBag.StudentName = studentName;
        ViewBag.StudentEmail = studentEmail;
        ViewBag.StudentDepartment = studentDepartment;
    }

    public JsonResult IsCourseNameExists(string CourseStudentCourse, string CourseStudentRegNo)
    {
        return Json(!db.CoursesStudents.Any(x => x.CourseStudentCourse == CourseStudentCourse && x.CourseStudentRegNo == CourseStudentRegNo), JsonRequestBehavior.AllowGet);
    }    

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
使用System.Collections.Generic;
使用System.Linq;
使用System.Web.Mvc;
使用大学应用程序上下文;
使用大学应用程序。模型;
命名空间UniversityApplication.Controller
{
公共课程学生控制员:控制员
{
私有ApplicationContext db=新的ApplicationContext();
公共行动结果学生课程()
{
GenerateDropDownValue();
返回视图();
}
[HttpPost]
[ValidateAntiForgeryToken]
公共行动结果学生到课程([Bind(Include=“CourseStudentID,CourseStudentRegNo,CourseStudentName,coursestudentmail,CourseStudentDepartmentCode,CourseStudentCourse,CourseStudentRegDate”)]coursestudentcoursestudent
{
GenerateDropDownValue();
if(ModelState.IsValid)
{
db.courseStudent.Add(courseStudent);
db.SaveChanges();
ModelState.Clear();
返回视图();
}
ModelState.Clear();
返回视图();
}
私有void GenerateDropDownValue()
{
List allRegisteredStudents=新列表();
列出学生=新建列表();
列出所有课程=新建列表();
字符串studentName=“”;
字符串studentEmail=“”;
字符串studentDepartment=“”;
使用(ApplicationContext db=newapplicationContext())
{
allRegisteredStudents=db.Students.OrderBy(a=>a.StudentRegNo.ToList();
}
foreach(所有注册学生中的var学生)
{
学生们,加上(
新建SelectListItem()
{
Value=student.StudentRegNo,
Text=student.StudentRegNo
}
);
}
ViewBag.Students=学生;
ViewBag.CourseCode=新选择列表(所有课程,“CourseCode”、“CourseName”);
ViewBag.StudentName=StudentName;
ViewBag.StudentEmail=StudentEmail;
ViewBag.StudentDepartment=StudentDepartment;
}
public JsonResult IsCourseNameExists(字符串CourseStudentCourse,字符串CourseStudentRegNo)
{
返回Json(!db.coursestudents.Any(x=>x.CourseStudentCourse==CourseStudentCourse&&x.CourseStudentRegNo==CourseStudentRegNo),JsonRequestBehavior.AllowGet;
}    
受保护的覆盖无效处置(布尔处置)
{
如果(处置)
{
db.Dispose();
}
基地。处置(处置);
}
}
}

这是我的看法,

@model UniversityApplication.Models.CourseStudent

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>CourseStudent</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.CourseStudentRegNo, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CourseStudentRegNo, @ViewBag.Students as SelectList, "Select Student", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CourseStudentRegNo, "", new { @class = "text-danger" })
        </div>
    </div>        

    <div class="form-group">
        @Html.LabelFor(model => model.CourseStudentCourse, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CourseStudentCourse, @ViewBag.CourseCode as SelectList, "Select Course", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CourseStudentCourse, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CourseStudentRegDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.CourseStudentRegDate, new { @class = "date form-control", @readonly = "true" })
            @Html.ValidationMessageFor(model => model.CourseStudentRegDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Enroll" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
@section Scripts {

<script src="~/Scripts/jquery.validate.date.js"></script>
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
@Scripts.Render("~/bundles/jqueryval")

<script>

$(document).ready(function () {
    $('.date').datepicker({ dateFormat: "dd/mm/yy" });
});
</script>

}
@model university application.Models.CourseStudent
@{
ViewBag.Title=“创建”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
创造
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
课程学生

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.CourseStudentRegNo,htmlAttributes:new{@class=“controllabel col-md-2”}) @Html.DropDownListFor(model=>model.CourseStudentRegNo,@ViewBag.Students作为SelectList,“selectstudent”,new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.CourseStudentRegNo,“,new{@class=“text danger”}) @LabelFor(model=>model.CourseStudentCourse,htmlAttributes:new{@class=“controllabel col-md-2”}) @Html.DropDownListFor(model=>model.CourseStudentCourse,@ViewBag.CourseCode作为SelectList,“选择课程”,新建{@class=“form control”}) @Html.ValidationMessageFor(model=>model.CourseStudentCourse,“,新{@class=“text danger”}) @LabelFor(model=>model.CourseStudentRegDate,htmlAttributes:new{@class=“controllabel col-md-2”}) @TextBoxFor(m=>m.CourseStudentRegDate,新的{@class=“date form control”,@readonly=“true”}) @Html.ValidationMessageFor(model=>model.CourseStudentRegDate,“,新的{@class=“text danger”}) } @ActionLink(“返回列表”、“索引”) @节脚本{ @Scripts.Render(“~/bundles/jqueryui”) @style.Render(“~/Content/cssjqryUi”) @Scripts.Render(“~/bundles/jqueryval”) $(文档).ready(函数(){ $('.date').datepicker({dateFormat:“dd/mm/yy”}); }); }
我建议通过自定义数据注释来实现验证,而不是通过JsonResult方法使用自定义远程验证

有关如何通过数据注释创建自定义验证,请参阅此链接:

如果验证没有成功,那么您将使用无效的模型状态,并且不必担心错误。它还使您的体系结构更加安全

此外,作为最佳审慎监管机构
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
@model UniversityApplication.Models.CourseStudent

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

//Rest codes