gpt4 book ai didi

c# - 远程验证显示错误消息但仍让表单提交并保存在数据库 MVC 5

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:48 24 4
gpt4 key购买 nike

情况是,Student Reg 的组合。否。 并且选择类(class) 始终是独一无二的。

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

第一个预期结果:

将出现“所选学生已参加此类(class)”的错误消息。

第二个预期结果:

它将阻止提交表单,直到选择了之前未保存在数据库中的不同组合。

当前结果:

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

enter image description here

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

能否请您给出解决方案,因为我可以得到第二个预期结果?

提前致谢。

为了便于阅读,我排除了所有与姓名、电子邮件和部门相关的代码、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; }
}
}

这是我的 Controller ,

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

这是我的观点,

@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>

}

最佳答案

与其通过 JsonResult 方法 IsCourseNameExists 使用自定义远程验证,不如通过自定义数据注释 实现验证。

引用此链接了解如何通过数据注释创建自定义验证:Custom Validation Data Annotation Attribute

如果验证不成功则使用它,那么您将拥有无效的模型状态并且您无需担心该错误。它还使您的架构更加安全。

此外,作为最佳实践,您还应该在 Controller 的服务器端进行相同的检查(您在 IsCourseNameExists 方法中进行的检查),就在之前您正在保存到数据库。 注意:如果您只执行此检查,即使您的要求得到满足。

关于c# - 远程验证显示错误消息但仍让表单提交并保存在数据库 MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com