I have an issue that is probably just due to my lack of experience with ASP.NET MVC, but it's one I have been trying to resolve for a bit now.
I have a Code First database set up that doesn't differ very much from the first tutorial on asp.net (http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4). Basically the problem that I'm having is upon trying to create a new record in the database via the "Create" page, the ID is set to 0, which makes the ModelState invalid.
Relevant code: Model:
public class Evt
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string GeoDescription { get; set; }
public decimal Longitude { get; set; }
public decimal Latitude { get; set; }
public DateTime Date { get; set; }
}
Controller:
[HttpPost]
public ActionResult Create(Evt evt)
{
if (ModelState.IsValid) // This is returning false because ID is 0
{
db.Evts.Add(evt);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(evt);
}
I can add the View code as well upon request, but it's basically just the auto-generated code from the Model.
If anyone has any ideas, I'd greatly appreciate it!
Thanks,
Jeff
Edit: I do not reference the ID in my "Create" view at all, and adding it as a hidden form value did not solve my problem either.
Update: I have been able to circumvent the error by adding
if (!ModelState.IsValid && evt.ID == 0) ModelState.Clear();
above the if
statement in Create
, but this removes all client-side validation and is obviously not ideal. It does show that the record is properly inserted with an incremented ID once it hits the server though.