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

I submit the form to my ASP.NET MVC 3 server using a JavaScript handler (I use jQuery) and get error responses from the server in another JavaScript handler. I am wondering how should I display error messages as a result of the presentation of a form in a view? I would prefer to use some standard ASP.NET MVC 3 construct / construct.

EDIT

Please note that I want to display error messages from the server received in the JavaScript error handler function.

+4
source share
5 answers

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

Scroll down to "Enable client-side validation."

In your view, you will have code that looks like this:

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

UPDATE

It seems that the OP is interested in custom messaging. There is no MVC construct for this kind of custom message. It's best to just create your own messaging zone and write messages to it in your callback function. Shouldn't be too hard!

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

Assuming you are using jQuery validation, which comes with MVC solution templates, in your javascript handler you will have to add errors to the validator. There is a showErrors method on the validator .

On the client side :

 var formSubmitCallback = function(result){ var validator = $(this).data('validator'); if(!result.IsValid && validator) validator.showErrors(result.Errors); // uses jquery validator to highlight the fields // process the rest of the result here // if result.Action == ActionTypes.Redirect // location.href = result.Url // etc } 

Now I had to standardize the result object from the server to return a json object formatted with { "FieleName": "Error Message" } . I built several Controller and ViewModel extensions on the server side to accomplish this.

On the server side :

 public ActionResult SomeAction(Model someModel){ if(ModelState.IsValid) // save else // other stuff // always return this.AjaxSubmit. // Extension function will add Errors, and IsValid to the response data return this.AjaxSubmit(new ClientAction{ Action = ClientActionType.Redirect, Url = "/Some/Redirect/Route" }); } 

Note: looking back, I wrote some custom code to make it work. In the end, I will add the client and server code along with examples on github. But this is a general idea.

The server classes and extension you will need are below

 // GetAllErrors is a ModelState extension to format Model errors for Json response public static Dictionary<string, string> GetAllErrors(this ModelStateDictionary modelState) { var query = (from state in modelState where state.Value.Errors.Count > 0 group state by state.Key into g select new { FieldName = g.Key, FieldErrors = g.Select(prop => prop.Value.Errors).First().Select(prop => prop.ErrorMessage).ToList() }); return query.ToDictionary(k => k.FieldName, v => string.Join("<br/>", v.FieldErrors)); } // Controller result extension to return from actions public static JsonResult AjaxSubmit(this Controller controller, ClientAction action) { if (controller == null) return new JsonResult { Data = action }; var result = new AjaxSubmitResult { Errors = controller.ModelState.GetAllErrors(), IsValid = controller.ModelState.IsValid, ClientAction = action }; return new JsonResult{ Data = result }; } // Action to perform on the client after a successful, valid response public class ClientAction { public ClientActionType Action { get; set; } public string Url { get; set; } public string Function { get; set; } public object Data { get; set; } public Dictionary<string, string> Updatables { get; set; } } public enum ClientActionType { Redirect, Ajax, Function, Modal, Message, FunctionAndMessage } 
+1
source

The server should respond with a standard message. This message may contain a complete error message (HTML), which can then be displayed in an empty div that is part of your _Layout page:

 function(response) { if(response.Status === "error") { $("#errorContainer").html(response.ErrorHtml); } else { // the success handler } } 

The growth potential lies in the fact that the server can perform a standardized display of error messages. Of course, you can also display them as js popups / modal dialogs, etc.

The error message is formatted using CSS, which can be applied in general to #errorContainer and its contents.

You might want to claim that you clear the response using plain text from the server and add any html in the client through JS. This is possible, and probably works better with the "real" REST APIs. However, it does not allow the use of formatted error messages (for example, with links, etc.).

+1
source

I responded to something similar in the past to add error messages.

MVC Validation Manipulation Using JS and Dynamic DOM Elements

Since you want the errors returned from the server in what I assume to be your already known javascript method, just add

 var ul = $("#validationSummary ul"); ul.append("<li>Custom Error Message</li>")
var ul = $("#validationSummary ul"); ul.append("<li>Custom Error Message</li>") 
+1
source

How do i do this:

Create a base controller class and override the OnException handler

 public abstract class MyBaseController : Controller { protected override void OnException(ExceptionContext filterContext) { if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { // add my own status code Response.StatusCode = 550; // write the error message to the response Response.Write(filterContext.Exception.Message); // mark the exception as handled filterContext.ExceptionHandled = true; } base.OnException(filterContext); } } 

On the client side, on the finished document, I register a global handler for ajax errors

 $(document).ready(function(){ $.ajaxSetup({ error:function(x,e){ if(x.status==0){ alert('You are offline!!\n Please Check Your Network.'); }else if(x.status==404){ alert('Requested URL not found.'); }else if(x.status==550){ // <----- THIS IS MY CUSTOM ERROR CODE -------- alert(x.responseText); }else if(x.status==500){ alert('Internel Server Error.'); }else if(e=='parsererror'){ alert('Error.\nParsing JSON Request failed.'); }else if(e=='timeout'){ alert('Request Time out.'); }else { alert('Unknow Error.\n'+x.responseText); } } }); }); 

You can, of course, customize these methods to suit your needs. Hope this helps.

0
source

All Articles