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

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

    I had the same issue and managed to solve it by simply passing an empty instance of the view model to the view during the GET call of my Create method.

    //GET: DocumentTypes/{Controller}/Create
        public ActionResult Create()
        {
            return View(new DocumentTypeViewModel());
        }
    
        //POST: DocumentTypes/{Controller}/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(DocumentTypeViewModel viewModel)
        {
            if(ModelState.IsValid) {
    
                var result = AddDocumentType(viewModel);
                if(!result.HasValidationErrors) {
                    return RedirectToAction("Index");
                }
    
                ModelState.Update(result);
    
            }
    
            return View(viewModel);
        }
    

    And then in my view, I ensure that I have

    @Html.HiddenFor(m => m.ID)
    

    This way I don't have to explicitly specify Bind attributes

提交回复
热议问题