Prashanth Prashanth - 2 months ago 19
Ajax Question

How to call a method in c# class by jQuery Ajax without using MVC,WebForms concepts

I need to call a C# method by using attribute [WebMethod] and it should not use MVC, WebForms, API. It should be a clean c# class (.CS), HTML file.

Here is my

WebMethod
:

[WebMethod]
public string GetMessage() // Home.CS
{
return "GOGO";
}


Here is my ajax code:

<head> //HTML and Ajax
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function GetMessage() {
$.get("/Home/GetMessage", function (data) {
$("p").html(data);
});
}
</script>
</head>
<body>
<input type="button" onclick="GetMessage()" value="Get Message" />
<p></p>
</body>

Answer

I think you need a .net webservice .Works same like you want ..not webform/MVC ..Let WebService1.asmx and HTMLPage1.htm are in same directory.

Make sure you uncomment the line [System.Web.Script.Services.ScriptService] WebService1.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace StackOverflow_Solve.Services
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetMessage()   // Home.CS 
        {
            //return "GOGO";
            Context.Response.Output.Write("Hello World");
            Context.Response.End();
            return string.Empty;
        } 
    }
}

and HTMLPage1.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<head> //HTML and Ajax 
<title></title>

 <script>
     function GetMessage() {
         //Load jQuery($) to Use 
         $(function() {
             $.get("WebService1.asmx/GetMessage", function (data) {
                 console.log(data);
                 $("p").html(data);
             });
         });

     }
 </script>
</head>
<body>
    <input type="button" onclick="GetMessage()" value="Get Message" />
    <p></p>
</body>
</body>
</html>
Comments