Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c# - Required option with TryUpdateModel still saves into the db, when not inserting anything in the fields for the model

[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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...