[Required] on properties with an TryUpdateModel doesn't work.
I have a model where I'm using [Required] for each property.
Then in the Controller I use an TryUpdateModel. What I think that should happen was that the Employee wasn't saved into the db and it would say that the fields are required. But it does. With null values
public class Employee
{
//[Required] betyder at den er p?kr?vet
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Gender { get; set; }
[Required]
public string City { get; set; }
//Med sp?rgsm?l efter giver den mulighed for at DateOfBirth kan v?re null
[Required]
public DateTime? DateOfBirth { get; set; }
}
My Controller
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
Employee employee = new Employee();
//ved at bruge TryUpdateModel istedet for UpdateModel
TryUpdateModel(employee);
if (ModelState.IsValid)
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
employeeBusinessLayer.AddEmployee(employee);
return RedirectToAction("Index");
}
return View();
}
question from:
https://stackoverflow.com/questions/65602454/required-option-with-tryupdatemodel-still-saves-into-the-db-when-not-inserting 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…