Search code examples
javascripthtmlasp.net-mvchtml-helper

How to show error in View if the Controller fails ? ASP.NET MVC


On the server-side I have a transaction which returns a JsonResult:

public JsonResult DoStuff(Guid id, string userInputText)
{
     var product = _repository.Product(id); //busines logic

     //Only a specific product must have userInputText <= 10 characters. 
     //Other products may have as many characters as the user wants.
     if(product == Enum.SpecificProduct && userInputText.Count() > 10)
     {
          //The user input text comes from the View...
          //If it has more then 10 characters, need to send the errorMessage to the View.
          return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
     }

     //Otherwise, do stuff on the product... 

     //and return success at the end.
     return Json(new { success = true });
}

On the other hand, on the client-side I have this:

using (Ajax.BeginForm("DoStuff", ajaxOptions))
{
    <span>Enter the text:</span>
    @Html.TextArea("userInputText", new { onkeyup = "SyncContents(); return false;" })

    <input type="submit" value="Add" />
    <!-- error message should be displayed here-->
}

This is the AjaxOptions:

var ajaxOptions= new AjaxOptions
{
    OnSuccess = "reload",
    OnFailure = "FailMessage"
};

If the entered text have more then 10 characters, when the "Add" button is pressed, the Controller is being executing the code on the server-side and fails, how can I get the errorMessage from there and use it here, in the View, to inform the user ?

I tried to alert a message:

<script>
    function FailMessage() {
        alert("Fail Post");
    }
</script>

But no pop-up "Fail post" appears.

Best regards.


Solution

  • The problem here is the Ajax helper thinks all your responses are successful. Your controller action is returning HTTP 200 so there isn't a problem.

    https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.onfailure(v=vs.118).aspx#P:System.Web.Mvc.Ajax.AjaxOptions.OnFailure

    AjaxOptions.OnFailure Property

    This function is called if the response status is not in the 200 range.

    So you'll need to use the success handler and explicitly check the JSON success parameter.

    Or have your action change the HttpStatusCode for the response.

    if (notValid)
    {
        Response.StatusCode = 400;  // Bad Request
        return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
    }
    

    But for a validation error here I'd just check the for an error in the success handler.

    And yes, you should validate on the client and on the server.