Reputation: 51
how to edit in MVC ,i waana change other property like name,address but keeping unique email, contract that i have created before the model class is given below....
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; }
the controller for edit is also here
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);
}
what can be done for this problem?
Upvotes: 2
Views: 81
Reputation: 1533
You should create StudentForUpdate, then your update Action method will looks like
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);
}
In this case, email will never be changed.
Upvotes: 1