Asp MVC - "The Id field is required" validation message on Create; Id not set to [Required]
- by burnt_hand
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);
}