"The Id field is required" validation message on Create; Id not set to [Required]
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 va开发者_如何转开发lid 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);
}
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
}
I ran into this issue with a form in which I was adding "objects" to a list dynamically. Therefore, our users were able to add, remove or update. It all worked well except for the cases when new items were created. For this reason, in my case, excluding the Id property was not an option. The solution was to make the ID Nullable:
public int? Id { get; set; }
This way existing items will have a value and new ones will have null instead. Good stuff.
Great question and answers, saved my ... behind. I need to add something, though:
Instead of
[Bind(Exclude = "Id")]
I think it's better to use
[Bind(Include = "Prop1, Prop2, Prop3, etc")]
.. where Prop1, Prop2 and Prop3 are THE ONLY properties that you want to be bound at the action level.
Since this is white-listing as opposed to black-listing. White-listing is better, safer. This way you also solve the risk of over posting and under posting too. See Brad Wilson's post.
[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
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
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
add ? to int
[Key]
[HiddenInput(DisplayValue = false)]
public int? ID { get; set; }
Check in your view. Remove if your have hiddenfieldfor id field. This is used only for editing. @Html.HiddenFor(Model => Model.Id)
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.
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.
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.
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 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.
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?
Before check ModelState.IsValid remove 'Id' from ModelState.
ModelState.Remove("Id");
精彩评论