2011-01-28 74 views
2

出于某种原因,我的标识列“ID”得到MVC3验证?为什么会发生这种情况,我没有指定它是必需的。我有这个“@ Html.HiddenFor(model => model.Id)”在我看来,这不应该导致任何问题。MVC3验证

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

请大家帮忙。

回答

1

我想通了。我的课,我有包装(视图模型)类,像这样:

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; } 

我不得不加入这行:默认情况下隐藏字段

this.Admin = new Admin(); 

现在得到0。这是正确的:)。 感谢

4

值类型由MVC框架隐式验证。

要关闭此设置,请将DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes设置为false。

0

您可以在元数据如下指定要排除的属性:

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

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

} 
0

或者,也许,只是声明为可为空,然后让SQL Server的照顾值的身份字段与它为空。这就是我一直在做...

public int? Id { get; set; } 
0

上你的身份证只需添加关键属性

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