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

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

提交回复
热议问题