asp.net mvc - when - “The Id field is required” validation message on Create; Id not set to




mvc post tutorial (10)

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 {get;set;}

[Required]
public string Message {get; set}

On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action.

The ModelState says that "The Id field is required", but I haven't set that to be so. Is there something automatic going on here?

EDIT - Reason Revealed

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults

EDIT - Update Model technique

I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that.

    [HttpPost]
    public ActionResult Add(Venue collection)
    {
        Venue venue = new Venue();
        if (TryUpdateModel(venue, null, null, new[] { "Id" }))
        {
            _service.Add(venue);
            return RedirectToAction("Index", "Manage");
        }
        return View(collection);
    }

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.


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


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.


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


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


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.


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.


The Id should be sent from the client as 0. The model does not have a problem with Id=0, this is the default of int. The problem is that he does not see the value coming from the client or it's coming with space or null. I have an input hidden that represents the Id (or in complex object NestedPropertyId/NestedProperty.Id) so I make sure it starts with a value of zero.

<input type="hidden" id="id" value="0" />
<input type="hidden" id="eventId" value="0"/>
<input type="hidden" id="contactId" value="0"/>

Also when Ireset the form to Add New entity in the client side, I make sure to initialize the hidden with zero.

Hope this helps somone.

Efy


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?

add ? to int

[Key]
[HiddenInput(DisplayValue = false)]
public int? ID { get; set; }