Search code examples
c#asp.netajaxwebmethod

Create small single page Web API without MVC?


I have a limitation to one .aspx file and corresponding script file in C#.

I don't know how to use these WebMethods to achieve something like this:

Request Header: "http://localhost:8888/singlepage.aspx/file/8/items",
Type: "POST",
Data: {Description,Price}

Is it even possible without MVC?


Solution

  • You can use ASP.NET AJAX Page Methods to create page-hosted web service methods, like this:

    [WebMethod]
    public static void SaveDescriptionAndPrice(string description, decimal price)
    {
        // Do something here to save values
    }
    

    Now in your .aspx page, you can invoke the ASP.NET AJAX Page Method by using the jQuery .ajax() function, like this:

    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "singlepage.aspx/SaveDescriptionAndPrice",
            data: "{'description':'This is a fake description.', 'price':12.99}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                // Do something interesting here.
            }
        });
    });
    

    Note: I hard-coded the values for the data, but you can create a JavaScript object to hold the values and stringify() them or use jQuery to select the values from DOM elements.