ASP.NET MVC - ModelState.IsValid is false, how to bypass?
asp.net-mvc, validation
Solution
This will exclude value from binding, but not validation:
public ActionResult CreateCustomer([Bind(Exclude = "Id")]GWCustomer customer)
Even when validation occurs, you can still correct ModelState by calling:
ModelState.Remove("Id");
It will remove entries related to Id and change `ModelState.Valid` property to true if only `Id` was causing errors.
Using data layer objects in view layer is not recommended. You should definitely think about creating dedicated view model, without `Id` field.
Problem
I have a small application where I am creating a customer ``` [Authorize] [AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateCustomer(GWCustomer customer) { if (string.IsNullOrEmpty(customer.CustomerName)) { ModelState.AddModelError("CustomerName", "The name cannot be empty"); } //... if (ModelState.IsValid) { //insert in db } } ``` My problem is that the `GWCustomer` object has an `Id`, which is primary key and cannot be null. This makes the validation framework flag it as an error. But it's not an error, I haven't created the customer yet, and for now is should be null until it gets saved. How do I bypass this? Or fix it? I never get to insert it in the DB because the `ModelState` is never valid. Edit I am using Linq to SQL, and a repository pattern.