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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With