What's the recommended way to display errors from JavaScript (jQuery) in ASP.NET MVC 3 views?

aknuds1 picture aknuds1 · Sep 2, 2011 · Viewed 7.8k times · Source

I submit a form to my ASP.NET MVC 3 server through a JavaScript handler (I use jQuery), and receive error responses from the server in another JavaScript handler. What I'm wondering is how I should display error messages, resulting from the form submission, in the view? I would prefer using some standard ASP.NET MVC 3 idiom/construct.

EDIT

Note that I want to display error messages from the server, received in a JavaScript error handler function.

Answer

Adam Terlson picture Adam Terlson · Sep 2, 2011

You can go the pure MVC way: http://www.asp.net/mvc/tutorials/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript

Scroll down to "Enabling Client-Side Validation."

In your View you'll have code that looks like this:

@Html.TextBoxFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)

UPDATE

Seems OP is interested in custom messaging. There isn't any MVC construct for this sort of custom messaging. Your best bet is to just create your own messaging area and write messages to it in your callback function. Shouldn't be too complicated!

$.ajax(..., function(data) {
    $('#errors').append('<p>' + data + '</p>');
});