views:

74

answers:

2

I have 2 actions, one for GET and the other handles POST requests.

Although I have validation on the client side, there are some things I check for on the server-side also (in my action method).

In the POST action, when I find errors etc. that I want to report back to the UI, what options do I have to send back messages/errors to the client side?


Note:

I am using the popular jQuery validation plugin als.

+1  A: 

I you are using Model binding from your View to your Post Action, it has built in validation that can be used for this.

Some people however prefer to do validation outside of the Model. To return these errors back to the View, you need to update the ModelState, then do the normal check if it is valid (contains errors):

    public Dictionary<string, string> ValidateEntry(Object obj)
    {
        var errors = new Dictionary<string, string>();

        if (string.IsNullOrEmpty(obj.Owner))
        {
            errors.Add("Owner", "You must select Owned By.");
        }
        //... whatever else
        return errors;
    }

     [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Object cap)
    {
       var errors = ValidateEntry(cap);
        if (errors.Count > 0)
        {
            foreach (var err in errors)
            {
                ModelState.AddModelError(err.Key, err.Value);
            }
        }
        if (ModelState.IsValid)
        {
           //... do if valid
        }
        return View(ViewModel);
    }
Carlton Jenke
+1  A: 

Some rules I go by when implementing validation in web applications/sites:

  • The validation should occur client side and server side
  • Server side validation should mirror the client side validation for users with scripting turned off
  • Even though the validation rules are enforced in two places the logic should not be duplicated

Going by those rules I use the following solution:

  • xVal (found from ScottGu's blog)
  • IDataError solution from Adam Schroder
  • Business rules are implemented in the model with DataAnnotations
  • The service may throw custom exceptions for unique business constraints

Its amazing how easy this is to use and how well it works. It uses the JQuery validation plugin transparently and just does what it is supposed to with minimal coding.

Client side validation in your view consists of:

<%= Html.ClientSideValidation<Foo>() %>

Server side validation in your action consists of

ModelState.IsValid
blu