Search code examples
c#ajaxdotnetnukeascx

Dotnetnuke - How to call method in code behind with Ajax


This is script

<script type="text/jscript">
function ajaxcall(e) {
    $.ajax({
        type: "POST",
        url: "/DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ value: "Vinay" }),
        dataType: "json",
        success: function (value) {
            alert(value.d);
        },
        error: function () { alert("Ajax Error"); }
    });
};

This is code behind:

    [WebMethod]
    public static string GetMethod(String value)
    {
        return value;
    }

When i call function from button. It show js alert Ajax Error

<input type="button" id="button" value="Test" onclick="ajaxcall()" />

I was tried replace /DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod by AddCity.ascx/GetMethod but it still not work !


Solution

  • You can't call a WebMethod from an ASCX usercontrol - IIS won't allow it. It must be in an ASPX page.

    If you don't need any security, you can create a generic handler (.ASHX file).

    public class CityHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var fn = context.Request.QueryString["action"];
            var newCity = context.Request.QueryString["city"];
    
            if (fn == "add")
            {
                // TODO: add city
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("OK");
        }
    
        public bool IsReusable
        {
            get { return false; }
        }
    }
    

    Then change your ajax code:

    $.ajax({
        type: "GET",
        url: "/DesktopModules/Modules/Admin/City/CityHandler.ashx?action=add&city=Vinay",
        success: function (value) {
            alert(value);
        },
        error: function () { alert("Ajax Error"); }
    });