开发者

Ajax with jquery, scriptmanager and webservice which return null

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á-žÁ-Ž]*$");
     开发者_JAVA技巧   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.)


I will suggest that you check below points to troubleshoot:

  1. First see if there are not any java-script errors. IE8 has developer tools that allow you script debugging or you can use Firefox & Firebug combo for the same.
  2. Check request/responses going from/to browser - use tools such Fiddler (or Firefox/Fiebug)
  3. There can be problem in your cool logic - so try to put 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 use debugger; 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜