model.Id)\" in my view, which" />
开发者

MVC3 Validation

开发者 https://www.devze.com 2023-02-07 13:39 出处:网络
For some reason my Identity column \"ID\" gets validated by MVC3? why is this happening when i did not specify it to be required.?? I have this \"@Html.HiddenFor(model => model.Id)\" in my view, which

For some reason my Identity column "ID" gets validated by MVC3? why is this happening when i did not specify it to be required.?? I have this "@Html.HiddenFor(model => model.Id)" in my view, which should not cause any issues.

public class User {
    public 开发者_如何学Cint Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}

please help.


Value types are implicitly validated by the MVC framework.

To turn this off set DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes to false.


I figured it out. for my class i have wrapper (viewmodel) class like so:

   public class AdminsEditViewModel<T>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AdminsEditViewModel"/> class.
        /// </summary>
        public AdminsEditViewModel()
        {
            this.Admin = new Admin();
            this.GroupIn = new List<int>();
            this.GroupNotIn = new List<int>();
        }

        /// <summary>
        /// Gets or sets Admin.
        /// </summary>
        public Admin Admin { get; set; }

I had to add this line:

this.Admin = new Admin();

now by default hidden field gets 0. which is correct :). thanks


You can specify in the MetaData the attributes you want to exclude as follows:

 [Bind(Exclude = "Id")]
 public class User {

     [Required]
     public string Name { get; set; }
     [Required]
     public string Email { get; set; }

 }


Or maybe, just declare it as a nullable and then let the SQL Server take care of values for the identity field with null on it. That's what i've been doing...

public int? Id { get; set; }


Just add key attribute on your Id

public class User {
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消