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

前端 未结 16 1323
盖世英雄少女心
盖世英雄少女心 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 18:00

    I also faced the same problem with you and now I already resolved this. With HttpGet you need to return a View will empty model. Such as

    [HttpGet]
    public ActionResult Add()
    {
        //Your code here
        return View(new Venue);
    }
    

    I hope it is useful with you.

    0 讨论(0)
  • 2020-12-07 18:00

    Before check ModelState.IsValid remove 'Id' from ModelState.

    ModelState.Remove("Id");
    
    0 讨论(0)
  • 2020-12-07 18:02

    add ? to int

    [Key]
    [HiddenInput(DisplayValue = false)]
    public int? ID { get; set; }
    
    0 讨论(0)
  • In my case, the problem was coming from the fact that ID was of a type string. Changing to an int (not nullable) fixed it for me. The string type was a result of reverse engineering a badly designed database.

    0 讨论(0)
  • 2020-12-07 18:03

    Above answers are correct. Any how every one follow different scenario .My solution is as follows for the same problem. If your ID is a primary key then you need to initiate it I mean to say when you are passing model to view in get method just create new object before it . It will set 0 to your ID instead of null.

    0 讨论(0)
  • 2020-12-07 18:07

    I just created a new MVC2 project, and added a simple POCO as well as a Controller and a View. From what I understand, you're using model binding to create the object, that is

    using System.ComponentModel.DataAnnotations;
    public class SimpleObject
    {
        public int Id {get;set;}
        [Required]
        public string Message { get; set; }
    }
    

    in the Controller we have

    [HttpPost]
    public ActionResult Create(SimpleObject created)
    {
        /// do something
    }
    

    and in the View, there is no editor for the ID field?

    This should not end up in any error messages. Instead, the Id is supposed to be set to default(int) which is 0. This works for me. What version of MVC2 are you using (the RC I assume)?

    Don't get me wrong: It is important to prevent the Id from being bound by the model binders since that would allow an attacker to tamper with the Id of the object. Nonetheless, the default model binder should not show the behaviour you describe.

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