新手问题,试图找出发送的电子邮件,并显示结果,似乎无法让它工作.
function SendPreview() { var value = CKEDITOR.instances['Source'].getData(); alert(value); var model = { EmailBody: value.toString(),EmailTo: $("#SendTo").val(),EmailSubject: $("#Subject").val() }; var request = $.ajax({ url: '/Campaign/SendPreviewEmail',async: false,type: 'POST',dataType: 'JSON',data: { model: JSON.stringify(model) },cache: false,success: function (data) { if (data) { alert("Message Sent"); } else { alert("Message Not Sent,Please check details"); } } }); }
[HttpPost] [ValidateInput(false)] public bool SendPreviewEmail(string model) { var e = new EmailPreview(); JavaScriptSerializer objJavascript = new JavaScriptSerializer(); e = objJavascript.Deserialize<EmailPreview>(model); if (!string.IsNullOrEmpty(e.EmailTo) && !string.IsNullOrEmpty(e.EmailSubject) && !string.IsNullOrEmpty(e.EmailBody)) { if (IsValidEmail(e.EmailTo)) { _mailService.SendMail(account.Email,e.EmailTo,e.EmailSubject,e.EmailBody,true); return true; } } return false; }
解决方法
假设这是ASP.Net MVC,你应该从你的动作中返回一个ActionResult(或者至少是从它派生的东西).下一个问题是返回true将意味着将在bool值上调用toString(),从而导致字符串“True”或“False”.请注意,这两个在javascript中等同于true.相反,返回包含结果标志的JSON.
在jQuery代码中你也设置了async:false,这是一个非常糟糕的做法.事实上,如果您检查控制台,您会看到浏览器有关其使用的警告.您应该删除该属性,以便异步进行AJAX请求.您还在ajax()调用中将dataType设置为JSON,但实际上是返回一个字符串.试试这个:
function SendPreview() { var value = CKEDITOR.instances['Source'].getData(); var model = { EmailBody: value.toString(),success: function (data) { if (data.emailSent) { // note the object parameter has changed alert("Message Sent"); } else { alert("Message Not Sent,Please check details"); } } }); }
[HttpPost] [ValidateInput(false)] public ActionResult SendPreviewEmail(string model) { var e = new EmailPreview(); var result = false; JavaScriptSerializer objJavascript = new JavaScriptSerializer(); e = objJavascript.Deserialize<EmailPreview>(model); if (!string.IsNullOrEmpty(e.EmailTo) && !string.IsNullOrEmpty(e.EmailSubject) && !string.IsNullOrEmpty(e.EmailBody)) { if (IsValidEmail(e.EmailTo)) { _mailService.SendMail(account.Email,true); result = true; } } return Json(new { emailSent = result }); }