views:

49

answers:

2

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?

+2  A: 

You should be able to write your code like...

if (TryUpdateModel(dinner, "Dinner")) {
    dinner.Description = dinner.Description.Replace("\n", "<br />");
    //... now it's over length limit

    if (TryValidateModel(dinner)) {
        dinnerRepository.Save();
        return RedirectToAction("Details", new { id=dinner.DinnerID });
    }
}

return View(dinner);

This gets rid of the try {} block and allows you to validate your model.

BuildStarted
Oh, I didn't know about TryValidateModel, will give it a shot. Thanks!
Chad
TryValidateModel is magic! Love how TryUpdateModel and TryValidateModel flow. Thanks a ton!
Chad
+2  A: 

FluentValidation

A_HREF
Thanks, looks nice. Will definitely look into it.
Chad