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

3

13

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;
    }
Mural answered 18/4, 2013 at 14:9 Comment(3)
please show your SendMessage action...Rattlebrained
Not sure what it has to do with the question... 8|Mural
b/c you cannot use onFailure unless you want to capture an http error. Want to understand how you return errorRattlebrained
A
6

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.

Assyrian answered 2/5, 2013 at 13:8 Comment(0)
D
2

To solve this in my own solution, I used the HttpStatusCodeResult class. Here is the code I have for reference:

try
{
    // Some code that can error
}
catch (Exception e)
{
    return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, e.Message);
}

// View
OnFailure = "alert(error);"

This should still trigger all of the normal error behavior on the client, including putting a 500 error in the browser console, and should work perfectly with the script you are already using to show your error.

Dagenham answered 15/11, 2016 at 23:1 Comment(0)
U
0

You could catch your exception in the controller and send an exact error message back. Something like:

[HttpPost]
public ActionResult SendMessage(string message)
{
    try 
    {
        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;
    } 
    catch (e)
    {
        throw new HttpException(500, e.Message);
    }
}

You may need to examine the response in this case and update your javascript showError accordingly.

Urge answered 18/4, 2013 at 17:19 Comment(1)
Thanks, but it's no different from what I have without try catch - it also returns html dump of entire error page. Not sure if OnFailure parameter of Ajax.BeginForm helper can handle the exception by just getting the error message only. Looks like it's not possible. Just weird, how is this supposed to work, if you always get html dump of error back from the controller... I dont want to have any TRY/CATCH blocks on purpose, I just want to propagate and output the system exception as is, but only error message, not the html content.Mural

© 2022 - 2024 — McMap. All rights reserved.