Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Blankman Avatar asked Jan 23 '23 21:01

Blankman


2 Answers

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() %>
like image 192
tvanfosson Avatar answered Jan 26 '23 10:01

tvanfosson


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

like image 33
mmx Avatar answered Jan 26 '23 10:01

mmx