jquery - How to display error message only in OnFailure of Ajax.BeginForm in MVC3? -
i have simple ajax form in mvc3 app, 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 action fails send message, throws exception. exception handled , displayed in showerror(error){} javascript function:
function showerror(error) { $("#error").text(error.responsetext); };
the problem is: error.responsetext html dump of entire error page.
i need display exception error message (whatever in ex.message in mvc3).
the implementation of "public actionresult sendmessage(string message) { }" irrelevant.
i need know how display exception's message in showerror(error) javascript handler.
thanks bunch.
[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; }
you cannot handle each , every exception in onfailure method. because onfailure called if response status not in 200 range. can handle scenario 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("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; }
here in code if mail send have returned response "success" else have returned actual error , in javascript have handled response this:
function loadmessages(error) { if (error == 'success') { alert("mail sent successfully"); } else { $("#error").text(error); }
hope you.
Comments
Post a Comment