Send exception message in Ajax.BeginForm MVC 4 script

I have a partial view containing an ajax form. The view simply adds and updates user information.

The controller sends the same partial view as the ActionResult.

I want to make an error message if the transaction was not successful. But it should still send a partial view, only this time with a message.

How will this be achieved?

code:

ManageUsers.cshtml

<div id="details"> @{ Html.RenderPartial("AddModifyUserPartialView"); } </div> @{ Html.RenderPartial("ListUsersPartialView"); } 

AddModifyUserPartialView.cshtml

 @using (Ajax.BeginForm("AddModifyUser", "Account", FormMethod.Post, new AjaxOptions() { UpdateTargetId = "details", OnFailure= "handleError", OnSuccess="handleSuccess" }, new { id = "useragentform", enctype = "multipart/form-data" })) { //form fields here <input type="submit" id="savebutton" name="savebutton" value="Add New User" /> } 

Also in a partial image:

 function handleError(ajaxContext) { var response = ajaxContext.get_response(); var statusCode = response.get_statusCode(); alert(statusCode); } 

Account controller

 try { SecurityManager.AddUpdateUserAgent(ua); } catch (Exception ex) { //how do I send the message back along with the partial view??? } return PartialView("AddModifyUserPartialView"); 
+6
source share
3 answers

Two parts to resolve this issue, create a new exception, let it throw a StatusException with your message and throw it when you catch the normal exception:

 try { SecurityManager.AddUpdateUserAgent(ua); } catch (Exception ex) { throw new StatusException("Your error message here") } return PartialView("AddModifyUserPartialView"); 

Override controller :: OnException and handle the exception, setting it to handle, setting the error code to 500, setting HttpContext.Response.StatusDescription in the StatusException message. For instance:

  protected override void OnException(ExceptionContext filterContext) { if (filterContext.Exception == null) return; Type exceptionType = filterContext.Exception.GetType(); if (exceptionType == typeof(StatusException)) { filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8; filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message; } } 

Then, in the OnFailure handler for Ajax.BeginForm, display the error parameter:

 function handleError(data){ //display data.errorThrown, data.statusCode, etc... } 

By setting the error code to 500 in the OverException override, AjaxForm will detect the error and go to your handler. We also set the StatusDescription in the override so that the message is available in the handleError callback.

+5
source

The answer above is ok. A simple alternative could be:

 if (gotAnError) { Response.StatusCode = (int) System.Net.HttpStatusCode.BadRequest; // Or another code return Json( new { message = "You did something wrong." } ); } 

for the (partial) controller and

 function ShowPartialLoadErrors(result) { var obj = $.parseJSON(response.responseText); alert(obj.message); } 

for presentation.

+3
source

It can be argued that since your request expects only a partial view, your action should always return a partial view. If you encounter an error, go to your View Model view, which is in an error state, and let your view display accordingly.

 AddUpdateUserVM vm = new AddUpdateUserVM(); try { SecurityManager.AddUpdateUserAgent(ua); } catch (Exception ex) { //log exception vm.HasError = true; vm.ErrorMessage = ex.Message; } return PartialView("AddModifyUserPartialView", vm); 

View:

 @if(Model.HasError) { <div>@Model.ErrorMessage</div> @* Or whatever you want to display *@ } @using (Ajax.BeginForm("AddModifyUser", "Account", FormMethod.Post, new AjaxOptions() { UpdateTargetId = "details", OnFailure= "handleError", OnSuccess="handleSuccess" }, new { id = "useragentform", enctype = "multipart/form-data" })) { //form fields here <input type="submit" id="savebutton" name="savebutton" value="Add New User" /> } 

The OnFailure AjaxOptions function will only occur when the server cannot be reached or responds with some other status code other than 200. Personally, I prefer not to use Ajax.BeginForm and write my own jQuery ajax requests and allow the server-side action method to return an object JSON containing either an error or the requested layout markup. It gives you complete control over what you return from the server and what you do with it on the client side.

0
source

Source: https://habr.com/ru/post/953699/


All Articles