Typical scenario, post to an action that checks ModelState.IsValid and if it is, saves to the DB. Validation rules are set as data annotations in the Model.
Here's my issue. I have a data field that can't be longer than 400 characters. The data annotations enforce this, as well as a jQuery validation on client side.
User enters 395 characters, including a few line breaks. My app, turns those newlines into <br />
tags. But that is after the UpdateModel()
is called. Since the <br />
tags are longer than the newlines, it passes validation on UpdateModel, but fails when it actually tries to save to the DB.
code essentially like this (from NerdDinner):
[HttpPost, Authorize]
public ActionResult Edit(int id, FormCollection collection) {
Dinner dinner = dinnerRepository.GetDinner(id);
try {
UpdateModel(dinner, "Dinner");
dinner.Description = dinner.Description.Replace("\n", "<br />");
//... now it's over length limit
dinnerRepository.Save();
return RedirectToAction("Details", new { id=dinner.DinnerID });
}
catch {
return View(dinner);
}
}
When the exception is thrown, the ModelState rule violations from the data annotations are not populated, so no message is shown to my users.
What's a good way to handle this?