Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - ModelState.IsValid is false, how to bypass?

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.

like image 795
Brian Hvarregaard Avatar asked Mar 07 '10 19:03

Brian Hvarregaard


2 Answers

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.

like image 60
LukLed Avatar answered Oct 14 '22 11:10

LukLed


Maybe you have this line in your view:

@Html.HiddenFor(model => model.Id)

Delete it and the view won't send that parameter with the model.

like image 29
Jorge Arana Avatar answered Oct 14 '22 12:10

Jorge Arana