0

I want to call a Code Behind method with JS. I already tried [WebMethod]. I referred this link. But my code behind is not getting called. I pasted code below so you can find out actual problem for that.

Javascript

<script type="text/javascript">

function sendMail()
{
var arr = [];
arr.push('foo');
arr.push('bar');
arr.push('bazz');

 $.ajax({
                type: "POST",
                url: "~/Modules/Masters/Email.aspx/SendMail",
                data: "{info:arr}", // passing the parameter 
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (retValue) {
                    // Do something with the return value from.Net method
                }
            });
}
</script>

Code Behind

[WebMethod]
public static string SendMail(string[] info)
{
    return "";
}

Does it need any library. I already have <script src="/js/jquery-1.9.1.js" type="text/javascript"></script> in my .Master file.

5
  • Do you get an error in Firebug? maybe in the Net tab? Commented Apr 4, 2014 at 9:14
  • @markpsmith No error. Commented Apr 4, 2014 at 9:15
  • I am assuming when you say Code Behind, this is a generic handler (.ashx?) and not the page code behind file? As you are trying to do a post using AJAX? Commented Apr 4, 2014 at 9:22
  • No, because the link I followed has aspx and not ashx, should I use ashx? Commented Apr 4, 2014 at 9:25
  • Your main issue has been spotted by Issac in his answer. You cannot use ~ in javascript, as that is used by ASP.NET to denote the root of the application Commented Apr 4, 2014 at 17:42

5 Answers 5

1

try removing the "~" from the url in your ajax call. I don't think javascript can handle it well.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct... ~ is used by ASP.NET as a shortcut for the root of the application, it is not something that can be used with javascript
0

There is a few things that can be wrong, firstly you will need a ScriptManager on your page too!

2 Comments

Yes, I have. Should I set some attribute for that?
Yes <asp:scriptmanager enablepagemethods="true" id="scpt" runat="server"></asp:scriptmanager> I've used this approach before, its slightly different but has the same effect -> techillumination.in/2013/07/… maybe see what the differnces between it and your solution is
0

i am sending mail from pure html page using wcf service may be useful to you please chk this code:

html page:

   $(document).ready(function () {
        $('#reqinfo').click(function () {
           // debugger;
            var emailto = document.getElementById("emailid").value;
            if (emailto != "") {


                $.ajax({

                    type: "GET",
                    url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
                    // data: dat,
                    Accept: 'application/json',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                    //    debugger;


                    },
                    error: function (result) {
                       // debugger;

                    }
                });
            }
            else {
                //your validation message goes here
                return false;
            }
        });
    });

Wcf service: IEmailService page

  [OperationContract]
    [WebInvoke(UriTemplate = "/EmailService1/emaildata?Email={Email}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    string emaildata(string Email);

wcf service code page:

public string emaildata(string Email)
    {
      //your email code.....
    }

Web.config code:

    <system.webServer>
   <defaultDocument>
   <files>
    <add value="Service1.svc" />

   </files>
   </defaultDocument>

  <handlers accessPolicy="Read, Execute, Script">
   <add name="ISAPI64" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
</handlers>
 </system.webServer>

 <system.serviceModel>
  <services>
   <service name="SampleService" behaviorConfiguration="ServiceBehaviour">
     <endpoint address="" binding="webHttpBinding" contract="IService1" name="samendpoint" behaviorConfiguration="AjaxBehaviour">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"   />

    </service>

    </services>

    <behaviors>

    <serviceBehaviors>
     <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true" />
    </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
    <behavior name="AjaxBehaviour">
      <webHttp/>

    </behavior>
     </endpointBehaviors>

     </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
       <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true"
      automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
      </standardEndpoints>
     </system.serviceModel>

and do't forget to add Factory setting in markup of wcf service by right click on wcf service in solution explorer and go to view mark up

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

like in my code i set for example:

<%@ ServiceHost Language="C#" Debug="true" Service="PSICMS.EmailService1" CodeBehind="EmailService1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

Comments

0

Try this:

[WebMethod]
public static string SendMail(string info)
{
    return "";
}

Here info has comma separated values, you can split them and use.

Comments

0

Everything looks fine as far as calling the method. I'm assuming that your path to the method is incorrect. When I use this approach, the [WebMethod] would live in the code-behind of the same page, so I would use url: "Email.aspx/SendEmail I would also add an error handler to your $.ajax call to help with debugging. add this after your success handler. error: function(a,b,c){alert(a.responseText);} this should tell you what the problem is. You also don't need a script manager to make any of this work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.