如何只在MVC3中的Ajax.BeginForm的OnFailure中显示错误消息?

mon*_*tro 12 jquery ajax.beginform asp.net-mvc-3

我在我的MVC3应用程序中有这个简单的ajax表单,它发送电子邮件消息:

@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" />
}
Run Code Online (Sandbox Code Playgroud)

如果操作无法发送消息,则会抛出异常.异常处理并显示在showError(error){} javascript函数中:

function showError(error) { 
    $("#error").text(error.responseText);
};
Run Code Online (Sandbox Code Playgroud)

问题是:error.responseText是整个错误页面html转储.

我只需要显示异常错误消息(MVC3中ex.Message中的任何内容).

"public ActionResult SendMessage(string message){}"的实现是无关紧要的.

我需要知道如何只在showError(错误)javascript处理程序中显示异常的消息.

谢谢一堆.

    [HttpPost]
    public ActionResult SendMessage(string message)
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("sender@gmail.com");
        mail.Subject = "Some Message";
        mail.Body = message;
        mail.To.Add("recepient@gmail.com");
        SmtpServer.Send(mail);
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

Jit*_*mar 6

您无法处理OnFailure方法中的每个异常.因为如果响应状态不在200范围内,则调用OnFailure.所以你可以像这样处理你的场景:

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

    }
Run Code Online (Sandbox Code Playgroud)

在这段代码中,如果邮件发送成功,那么我已经返回响应"成功",否则我已经返回实际错误,并在javascript中我已经处理了这样的响应:

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

希望这会帮助你.


Flo*_*min 0

您可以在控制器中捕获异常并发送回准确的错误消息。就像是:

[HttpPost]
public ActionResult SendMessage(string message)
{
    try 
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("sender@gmail.com");
        mail.Subject = "Some Message";
        mail.Body = message;
        mail.To.Add("recepient@gmail.com");
        SmtpServer.Send(mail);
        return null;
    } 
    catch (e)
    {
        throw new HttpException(500, e.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可能需要检查响应并showError相应地更新您的 JavaScript。