views:

76

answers:

1

I'm working through the NerdDinner ASP.NET MVC 1.0 example.

I have it all working apart from Exception handling. I've modified it very slightly for my own benefit, but basically, when I create a new record that violates a validation rule, I get an ApplicationException being thrown - instead of the form highlighting the incorrect field.

partial void OnValidate(ChangeAction action)
{
    if (!IsValid)
        throw new ApplicationException("Rule violations prevent saving");
}

.. basically the code is coming in here (throw new exception) and then VS breaks to the exception.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
    Customer c = customerRepository.GetCustomer(id);
    try
    {
        UpdateModel(c);
        customerRepository.Save();
        return RedirectToAction("Details", new { id=c.CustomerId });
    }
    catch
    {
        ModelState.AddRuleViolations(c.GetRuleViolations());
        return View(c);
    }
}

Can anyone hazard what I've done wrong?

EDIT: I should add that I did look through the few related posts here on SO but none were quite the same issue as far as I could see.

+1  A: 

I think that is correct. But you could also use the property ModelState.IsValid to avoid throwing an exception.

See these links too:

Validating Model Data in an MVC Application

http://stackoverflow.com/questions/881281/what-is-modelstate-isvalid-valid-for-in-asp-net-mvc-in-nerddinner

Andersson Melo
Thank you. That helped, is working ok now.
pierre