Ajax 与 jquery、scriptmanager 和 webservice 返回 null
我没有从 WebService 中获取数据,我也不知道为什么。 :/
我在我的 MasterPage.master 中有这个:
<asp:ScriptManager id="scriptMng" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/Mailing.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel runat="server" id="mailFormUpdatePanel" updateMode="Conditional">
<ContentTemplate>
/* form */
</ContentTemplate>
</asp:UpdatePanel>
在我的 Mailing.asmx 中我有这个:
<%@ WebService Language="C#" CodeBehind="~/App_Code/Services/Mailing.cs" Class="Mailing" %>
在我的 Mailing.asmx.cs 中我有这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Mail;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for Mailing
/// </summary>
[WebService(Namespace = "http://ktwebstudio.cz/WebServices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Mailing : System.Web.Services.WebService
{
[WebMethod()]
public string Mail(string fromName, string fromSurename, string fromEmail, string fromPhone, string phoneTimeFrom, string phoneTimeTo, string selectedJob, string mailMsg)
{
if (fromName.Trim() != "" && fromSurename.Trim() != "" && fromName != "Jméno" && fromSurename != "Příjmení" && fromEmail.Trim() != "" && fromEmail != "E-mailová adresa (povinné)")
{
bool error = false;
if (fromPhone.Trim() != "" && fromPhone != "Telefonní číslo (nepovinné)")
error = !IsNumber(fromPhone.Trim());
if (IsWord(fromName.Trim()) && IsWord(fromSurename.Trim()) && IsEmail(fromEmail.Trim()) && !error)
{
/*
some logic
*/
try { client.Send(mail); }
catch
{
return "Odesílání zprávy selhalo, zkuste prosím akci opakovat. <br />Při přetrvávajících problémech zkuste použít alternativní způsob kontaktování, který naleznetev sekci <a runat=\"server\" href=\"<%$RouteUrl:RouteName=contact%>\">kontakt</a>.";
}
return "Zpráva byla úspěšně odeslána, děkujeme.";
}
else
return "Vaše jméno, příjmení nebo jeden z Vášich vyplněných kontaktů obsahuje neplatné znaky.";
}
else
return "Musíte vyplnit Vaše jméno, příjmení a kontaktní email.";
}
public bool IsWord(string word)
{
Regex mask = new Regex(@"^[a-zA-Zá-žÁ-Ž]*$");
return mask.IsMatch(word);
}
public bool IsEmail(string email)
{
Regex mask = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", RegexOptions.IgnoreCase);
return mask.IsMatch(email);
}
public bool IsNumber(string number)
{
int num;
return int.TryParse(number, out num);
}
}
所以在我的 Masterpage.master.cs 中我测试浏览器是否支持 JS,如果不支持我调用来自OnClick方法的Web服务在哪里,我认为这是可以的:(如果不支持JS,不要问我为什么我不想拥有这个)
Mailing mail = new Mailing();
statusMsgLbl = mail.Mail(txtName.Text, txtSurename.Text, txtMail.Text, txtPhone.Text, startTime.SelectedValue, endTime.SelectedValue, selectJob.SelectedValue, txtMessage.Text);
但是如果支持JS(我希望用户打开它)我在我的Masterpage.master 这个 jQuery 和 javascript 代码:
var msg;
Sys.Application.add_load(load);
function load() {
$('#submit').click(function () {
msg = Mailing.Mail($('#txtName').val(), $('#txtSurename').val(), $('#txtMail').val(), $('#startTime').val(), $('#endTime').val(), $('#selectJob').val(), $('#txtMessage').val());
});
}
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
function beginRequestHandler() {
$(document.createElement('div'))
.attr('id', 'overlay')
.width($('#formBox').width())
.height($('#formBox').height())
.css({ backgroundImage: 'url(/Static/Img/bc_overlay.png)', position: 'absolute', left: 0, top: 0, margin: "5px", textAlign: "center", color: "#000", display: "none" })
.append("<div id='loading' style='padding-top:100px'><strong>Odesílám</strong><br /><img src='Static/Img/ajax-loader.gif' width='33px' height='33px' alt='loading' /></div>")
.show(500)
.prependTo($('#formBox'));
$('#formBox').css('position', 'relative');
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler() {
$('#loading').delay(2000).slideUp(800);
$('#overlay').append("<div style='padding-top:100px'><strong id='statusMsg'></strong></div>");
if (msg != null)
$('#statusMsg').css('display', 'none').delay(2800).fadeIn(300).text(msg);
else
$('#statusMsg').css('display', 'none').delay(2800).fadeIn(300).text("Problém");
$('#overlay').delay(6000).hide(800);
}
第一个函数使用我的 WebService。
第二个函数在 beginRequest 时做一些很酷的事情。
最后一个函数也做一些很酷的事情endRequest + 写入错误/成功消息是什么时候..但我没有从 Mailing.asmx.cs 获取字符串,我不知道为什么。 :-/ 我放入最后一个函数 if(msg != null) ...所以我知道 msg 为 null,如果你能告诉我原因,我将非常感激。
(我也在 jquery 中通过 $.ajax 尝试过,但我得到了 500 ERROR 所以我将这种方式与 Sys.WebForms.PageRequestManager 一起使用。)
I dont get from my WebService data back and I dont know why. :/
I have in my MasterPage.master this:
<asp:ScriptManager id="scriptMng" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/Mailing.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel runat="server" id="mailFormUpdatePanel" updateMode="Conditional">
<ContentTemplate>
/* form */
</ContentTemplate>
</asp:UpdatePanel>
In my Mailing.asmx I have this:
<%@ WebService Language="C#" CodeBehind="~/App_Code/Services/Mailing.cs" Class="Mailing" %>
In my Mailing.asmx.cs I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Mail;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for Mailing
/// </summary>
[WebService(Namespace = "http://ktwebstudio.cz/WebServices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Mailing : System.Web.Services.WebService
{
[WebMethod()]
public string Mail(string fromName, string fromSurename, string fromEmail, string fromPhone, string phoneTimeFrom, string phoneTimeTo, string selectedJob, string mailMsg)
{
if (fromName.Trim() != "" && fromSurename.Trim() != "" && fromName != "Jméno" && fromSurename != "Příjmení" && fromEmail.Trim() != "" && fromEmail != "E-mailová adresa (povinné)")
{
bool error = false;
if (fromPhone.Trim() != "" && fromPhone != "Telefonní číslo (nepovinné)")
error = !IsNumber(fromPhone.Trim());
if (IsWord(fromName.Trim()) && IsWord(fromSurename.Trim()) && IsEmail(fromEmail.Trim()) && !error)
{
/*
some logic
*/
try { client.Send(mail); }
catch
{
return "Odesílání zprávy selhalo, zkuste prosím akci opakovat. <br />Při přetrvávajících problémech zkuste použít alternativní způsob kontaktování, který naleznetev sekci <a runat=\"server\" href=\"<%$RouteUrl:RouteName=contact%>\">kontakt</a>.";
}
return "Zpráva byla úspěšně odeslána, děkujeme.";
}
else
return "Vaše jméno, příjmení nebo jeden z Vášich vyplněných kontaktů obsahuje neplatné znaky.";
}
else
return "Musíte vyplnit Vaše jméno, příjmení a kontaktní email.";
}
public bool IsWord(string word)
{
Regex mask = new Regex(@"^[a-zA-Zá-žÁ-Ž]*$");
return mask.IsMatch(word);
}
public bool IsEmail(string email)
{
Regex mask = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", RegexOptions.IgnoreCase);
return mask.IsMatch(email);
}
public bool IsNumber(string number)
{
int num;
return int.TryParse(number, out num);
}
}
So In my Masterpage.master.cs I test if browser support JS, if not i call web service from OnClick method where is this and i think that this was OK: (Dont ask me why I dont wanna have this if JS isnt supported)
Mailing mail = new Mailing();
statusMsgLbl = mail.Mail(txtName.Text, txtSurename.Text, txtMail.Text, txtPhone.Text, startTime.SelectedValue, endTime.SelectedValue, selectJob.SelectedValue, txtMessage.Text);
But if JS is supported (i hope that user have it turn on) I have in my Masterpage.master this jQuery and javascript code:
var msg;
Sys.Application.add_load(load);
function load() {
$('#submit').click(function () {
msg = Mailing.Mail($('#txtName').val(), $('#txtSurename').val(), $('#txtMail').val(), $('#startTime').val(), $('#endTime').val(), $('#selectJob').val(), $('#txtMessage').val());
});
}
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
function beginRequestHandler() {
$(document.createElement('div'))
.attr('id', 'overlay')
.width($('#formBox').width())
.height($('#formBox').height())
.css({ backgroundImage: 'url(/Static/Img/bc_overlay.png)', position: 'absolute', left: 0, top: 0, margin: "5px", textAlign: "center", color: "#000", display: "none" })
.append("<div id='loading' style='padding-top:100px'><strong>Odesílám</strong><br /><img src='Static/Img/ajax-loader.gif' width='33px' height='33px' alt='loading' /></div>")
.show(500)
.prependTo($('#formBox'));
$('#formBox').css('position', 'relative');
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler() {
$('#loading').delay(2000).slideUp(800);
$('#overlay').append("<div style='padding-top:100px'><strong id='statusMsg'></strong></div>");
if (msg != null)
$('#statusMsg').css('display', 'none').delay(2800).fadeIn(300).text(msg);
else
$('#statusMsg').css('display', 'none').delay(2800).fadeIn(300).text("Problém");
$('#overlay').delay(6000).hide(800);
}
First function use my WebService.
Second function do some cool things when is beginRequest.
And last function do some cool things too when is endRequest + write error / success message.. But i dont get my strings from Mailing.asmx.cs and I dont know why. :-/ I put into last function if(msg != null) ... So I know that msg is null and if u can tell me why, i will so grateful.
(I tried it by $.ajax in jquery too, but i got 500 ERROR so I use this way with Sys.WebForms.PageRequestManager.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您检查以下几点来排除故障:
alert
放入您的查看 js 代码以查看调用了哪些代码点。当然,您实际上可以使用任何脚本调试器(包括 Visual Studio)来添加断点并单步执行。如果您不知道,您可以在 js 中使用debugger;
语句来触发调试器 - 浏览器将提示您附加可用的调试器。因此,我更喜欢使用 jquery ajax 方法。这里有几篇文章可以帮助您开始使用它: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ 和 http://www.dotnetfunda.com/articles/article1127-consumer- web-service-webmethod-from-jquery-in-aspnet-.aspx
I will suggest that you check below points to troubleshoot:
alert
in your js code to see what code points are getting invoked. Of course, you can actually use any script debugger (including visual studio) to add break-points and step through. If you are not aware, you can usedebugger;
statement in your js to trigger debugger - browser will prompt you with available debuggers to attach.As such, I prefer using jquery ajax method. Here are couple of articles to help you to start with it: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ and http://www.dotnetfunda.com/articles/article1127-consuming-web-service-webmethod-from-jquery-in-aspnet-.aspx