ModelState.IsValid does not exclude required property

后端 未结 7 1338
猫巷女王i
猫巷女王i 2020-12-06 12:22

Im trying to exclude a required property(Password) so the modelstate dont validate that property, but for some reason it still validate even when i try to exclude it.

<
7条回答
  •  心在旅途
    2020-12-06 12:42

    I had success using the following method within ASP .NET MVC 2

    TryUpdateModel(user);
    ModelState.Remove("Password");
    if (!ModelState.IsValid) return PartialView(user);
    

    To keep the TryUpdate from binding to certain model properties you can create an inclusion template such as the one below:

    public interface IUserValidateBindable
    {
        string UserId { get; set; }
    }
    
    public class User : IUserValidateBindable
    {
        [Required]
        public string UserId { get; set; }
        [Required]
        public string Password { get; set; }
    }
    

    The update the TryUpodateModel call as follows:

    TryUpdateModel(user);
    

提交回复
热议问题