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 e开发者_开发问答mpty");
}
//...
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.
This is why I always say that the ViewModel objects (input and output) should be separated from the Domain Objects.
The input model should be validated in the way you are above; the domain object state should be validated before it gets written to the database (and exceptions thrown if it is somehow invalid).
精彩评论