Question

I have an aspx page I'm using to encapsulate a few functions. These functions are called in the page load, and selected by a string variable added to the POST request via jQuery.

My question is, how do I return an error code if, say, the POST request for some reason doesn't contain the required ID number, etc.

As well, I'd like to know if I'm doing this right (I have a form that needs the ability to add and remove IDs from a list, and I'm doing this by manipulating the session from this page I'm calling from jQuery).

What I have so far:

The calling page:

    function addItem(code) {
        $("#SubtypeTextbox").load(
            "../../src/ajax/Subtype.aspx",
            {
                Action: "Add",
                SID: code
            }
        );
    }

And the called page's aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Scripts_ajax_Subtype : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["Action"] == null)
        {
            Response.Clear();
            Response.StatusCode = 409;
            Response.TrySkipIisCustomErrors = true;
            Response.Write("<p class=\"Errors\">Action is required.</p>");
        }
        else if (Request.Form["SID"] == null)
        {
            Response.Clear();
            Response.StatusCode = 409;
            Response.TrySkipIisCustomErrors = true;
            Response.Write("<p class=\"Errors\">Subtype ID is required.</p>");
        }
        else
        {
            //Execute request
        }
    }
}
Was it helpful?

Solution

I would suggest that you investigate ASP.NET AJAX Page Methods. They are essentially web services hosted inside of an ASP.NET page, like this:

[WebMethod]
public static string GetDate()
{
    return DateTime.Now.ToString();
}

Now you can invoke the page method via jQuery, like this:

$.ajax({
    type: "POST",
    url: "YourPage.aspx/GetDate",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        // Do something interesting here.
    }
});

Note: ASP.NET AJAX Page Methods must be static and do not have an instance of the Page class, but they do not have access to the HttpContext.Current.Session object if you decorate the page method correctly.

Finally, ASP.NET AJAX Page Methods JSON-encode their responses, so you will not see any serialization code in the page method, because it is done automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top