How to display error message only in OnFailure of Ajax.BeginForm in MVC3?

monstro picture monstro · Apr 18, 2013 · Viewed 21.7k times · Source

I have this simple ajax form in my MVC3 app, that sends email message:

@using (Ajax.BeginForm("SendMessage", new AjaxOptions { 
    LoadingElementId = "wait", 
    OnSuccess = "loadMessages", 
    OnFailure = "showError" }))
{
    <input type="text" name="message" placeholder="Message" />
    <input type="submit" name="submit" value="Send" />
}

If the action fails to send a message, it throws the exception. The exception is handled and displayed in the showError(error){} javascript function:

function showError(error) { 
    $("#error").text(error.responseText);
};

The problem is: error.responseText is the html dump of the entire error page.

I need to display only the exception error message (whatever is in ex.Message in MVC3).

The implementation of "public ActionResult SendMessage(string message) { }" is irrelevant.

I need to know how to display the exception's message only in showError(error) javascript handler.

Thanks a bunch.

    [HttpPost]
    public ActionResult SendMessage(string message)
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("[email protected]");
        mail.Subject = "Some Message";
        mail.Body = message;
        mail.To.Add("[email protected]");
        SmtpServer.Send(mail);
        return null;
    }

Answer

Jitender Kumar picture Jitender Kumar · May 2, 2013

You cannot handle each and every exception in OnFailure method. Because OnFailure is called if the response status is not in the 200 range. So you can handle your scenario something like this:

    [HttpPost]
    public ActionResult SendMessage(string message)
    {
        MailMessage mail = new MailMessage();
        ActionResult response = null;
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("[email protected]");
        mail.Subject = "Some Message";
        mail.Body = message;
        mail.To.Add("[email protected]");
        try
        {
            SmtpServer.Send(mail);
            response = Content("Success");
        }
        catch (Exception ex)
        {
            response = Content(ex.Message);
        }
        return response;

    }

Here in this code if mail send successfully then I have returned response "Success" else I have returned the actual error and in javascript I have handled this response like this:

    function loadMessages(error) {
    if (error == 'Success') {
        alert("Mail Sent successfully");
    }
    else {
        $("#error").text(error);
    }

Hope this will help you.