“The Id field is required” validation message on Create; Id not set to [Required]

前端 未结 16 1315
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:18

This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2.

The POCO has the following properties:

public int Id          


        
相关标签:
16条回答
  • 2020-12-07 17:50

    I had the same issue, except i had three integer fields on my model. I managed to get around it by setting all my integer properties that were erroneously required to nullable ints.

    0 讨论(0)
  • 2020-12-07 17:53

    I have the same problem, using RC2 with a POCO. If you name a property Id but do not put an validation attributes on it but IsValid says it is required. If I name a property anything but Id this does not happen. Why should I have to Exclude Id?

    Thanks

    0 讨论(0)
  • 2020-12-07 17:55

    You can add the attribute:

     [Bind(Exclude = "Id")] 
    

    on the parameter in method rather than the class, that way on create you can exclude it and on edit it will still be mandatory:

    public ActionResult Create([Bind(Exclude = "Id")] User u)
    {
        // will exclude for create
    }
    
    public ActionResult Edit(User u)
    {
        // will require for edit
    }
    
    0 讨论(0)
  • 2020-12-07 17:55

    You can disable this implicit validation by setting the AddImplicitRequiredAttributeForValueTypes option on the DataAnnotationsModelValidatorProvider by adding the following to your Application_Start:

    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
    

    Further Reading:

    • Unrequired property keeps getting data-val-required attribute
    • ASP.NET MVC optional field being treated as required
    • Why MVC Model Binder set required for int, long values?
    0 讨论(0)
  • 2020-12-07 17:58

    Check in your view. Remove if your have hiddenfieldfor id field. This is used only for editing. @Html.HiddenFor(Model => Model.Id)

    0 讨论(0)
  • 2020-12-07 18:00
    [Bind(Exclude = "Id")]
    public class Hebe
    {
          public int Id {get;set;}
    
          [Required]
          public string Message {get; set}
    }
    

    By the way above it doesnt bind the Id Property for your model on create

    0 讨论(0)
提交回复
热议问题