开发者

How best to handle late data validation using asp.net MVC 2's data annotation validation?

开发者 https://www.devze.com 2023-01-18 01:11 出处:网络
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.

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?


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.


FluentValidation

0

精彩评论

暂无评论...
验证码 换一张
取 消