Hi @Harun Ergün,
You want to implement model validation, do you use the ValidationMessageFor attribute in the View?
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
You can refer to the following examples to see where your code is missing.
public class HomeController : Controller
{
private SchoolContext db = new SchoolContext();
public ActionResult Index()
{
return View(db.Students.ToList());
}
public ActionResult Edit(int Id)
{
var std = db.Students.ToList().Where(s => s.StudentId == Id).FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
var student = db.Students.ToList().Where(s => s.StudentId == std.StudentId).FirstOrDefault();
student.StudentName = std.StudentName;
db.SaveChanges();
return RedirectToAction("Index");
}
}
public class Student
{
public int StudentId { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(30, ErrorMessage = "error")]
public string StudentName { get; set; }
public int Age { get; set; }
}
You can also iterate over each error in the Catch loop to find out where the error is. code show as below:
try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.