gpt4 book ai didi

c# - 如何在 MVC 上执行编辑以保持某些值的独特性?

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:27 25 4
gpt4 key购买 nike

如何在 MVC 中编辑,我想更改名称、地址等其他属性,但保留我之前创建的唯一电子邮件、契约(Contract)模型类如下所示....

 public class Student

{

[Required]
public int StudentId { get; set; }
[Required]
[DisplayName("Name")]
public string StudentName { get; set; }
[Required]
[DisplayName("Email")]
[Remote("IsEmailUnique", "Student", ErrorMessage = "This email already exists")]
[RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Please enter a valid email address")]
public string StudentEmail { get; set; }
[Required]
[DisplayName("Contact No.")]
[RegularExpression("^(?!0+$)(\\+\\d{1,3}[- ]?)?(?!0+$)\\d{11,15}$", ErrorMessage = "Please enter valid phone no.")]
[Remote("IsContractNoUniue", "Student", ErrorMessage = "This Reg.No already exists")]
public string StudentContactNo { get; set; }
[Required]
[DisplayName("Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

public DateTime RegistrationDate
{
get { return (defaultDate == DateTime.MinValue) ? DateTime.Now : defaultDate; }
set { defaultDate = value; }
}

public string Address { get; set; }
[Required]
public int DepartmentId { get; set; }
[Required]
[DisplayName("Reg.No")]
[Remote("IsRegNoUnique", "Student", ErrorMessage = "This Reg.No already exists")]
public string StudentRegistrationNumber { get; set; }

public Department Department { get; set; }
public List<StudentEnrolledCourse> StudentEnrolledCourses { get; set; }

编辑 Controller 也在这里

public ActionResult Edit([Bind(Include = "StudentId,StudentName,StudentEmail,StudentContactNo,RegistrationDate,Address,DepartmentId,RegistrationNumber")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", student.DepartmentId);
return View(student);
}

如何解决这个问题?

最佳答案

您应该创建 StudentForUpdate,然后您的更新 Action 方法将如下所示

public ActionResult Edit([Bind(Include = "StudentId,StudentName,StudentContactNo,RegistrationDate,Address,DepartmentId,RegistrationNumber")] StudentForUpdate student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", student.DepartmentId);
return View(student);
}

在这种情况下,电子邮件将永远不会更改。

关于c# - 如何在 MVC 上执行编辑以保持某些值的独特性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52560259/

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