Blankman
Blankman

Reputation: 266960

server side validation, how to pass errors to view in MVC?

Using .net MVC and I am doing some server side validation in my Action that handles the form post.

What is a good technique to pass the errors back to the view?

I am thinking of creating an error collection, then adding that collection to my ViewData and then somehow weave some javascript (using jQuery) to display the error.

It would be nice it jQuery had some automagic way of display an error since this is a common pattern.

What do you do?

Upvotes: 4

Views: 5843

Answers (5)

Christian Dalager
Christian Dalager

Reputation: 6643

I use the builtin ModelState object hold my validation errors. Validation is done either in binding or by hand supported by manually adding the errors like this:

ModelState.AddModelError("LastName","Last name can't be Doe").

To support the ajax form post scenario, I have made an extension method to the ModelStateDictionary, GetErrors(), that returns a light ModelStateErrorsDTO object (a flattened version of the modelstate's validation errors suitable for json serialization).

When a form post is an ajax request I then return a json serialized ModelStateErrorsDTO.

On the jquery side I have written a helper function that places the validation errors next to the relevant inputfields using the default mvc css classes, i.e. input-validation-error.

This way you will be able to make unobtrusive ajaxforms with validation messages.

Hope this helps.

Upvotes: 0

Morph
Morph

Reputation: 1719

Not quite sure if it's what your looking for but there is a very easy to use form validation plugin for jquery at http://bassistance.de/jquery-plugins/jquery-plugin-validation/. It automagically displays error messages in red.

Ofcourse you still have to do server side validation, and pass back the errors. tvanfosson showed you how in his answer.

Upvotes: 0

omoto
omoto

Reputation: 1220

Yes it's good way but anyway you can put error message to your own ViewData["key"] = "Error on page...bla...bla...bla..."

<% if (!string.IsNullOrEmpty(ViewData["key"]+"")) { %>

<div>
Yor customized error template
</div

<% } %>

Upvotes: -1

tvanfosson
tvanfosson

Reputation: 532435

You want to add the errors to the ModelState as @Mehrdad indicates.

...
catch (ArgumentOutOfRangeException e)
{
    ModelState.AddModelError( e.ParamName, e.Message );

    result = View( "New" );
}

And include the ValidationSummary in your View

<%= Html.ValidationSummary() %>

Upvotes: 9

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

ViewData.ModelState is designed to pass state information (errors) from the controller to the view.

Upvotes: 1

Related Questions