Ivan
Ivan

Reputation: 261

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.

In my client side JQuery I have:

 $.post("test.aspx/testMethod",
        {
            name: "Donald Duck",
            city: "Duckburg"
        }
    );

In my server side (test.aspx.cs) method, I have

  public void testMethod()
{
    string name = Request.Form("name");
    string city = Request.Form("city");
}

But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."

How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.

Upvotes: 3

Views: 4806

Answers (5)

maplemale
maplemale

Reputation: 2036

There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:

In your javascript you just call the method:

PageMethods.SomeMethod('test');

Your "SomeMethod" would be a code behind method like this:

[WebMethod]
    public static string SomeMethod(string param1)
    {
        string result = "The test worked!";
        return result;
    }

Rules: You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:

<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />

Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.

Upvotes: 2

Ivan
Ivan

Reputation: 261

The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.

The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).

C# Default.aspx.cs (CODE BEHIND TO Default.aspx)

protected void Page_Load(object sender, EventArgs e)
{
    getText();
}

public void getText()
{
    if (HttpContext.Current.Request.Form.Keys.Count > 0)
    {   
        // Reset staticValue
        Class1.staticValue = "";

        Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
    // Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"

    }
}

STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)

public class Class1
{
    private static string myValue = "";
    public Class1()
    {
            //
        // TODO: Add constructor logic here
        //
    }

    public static string staticValue
    {
        get
        {
            return myValue;
        }

        set
        {
            myValue = value;
        }
    }
}

Upvotes: 0

Ivan
Ivan

Reputation: 261

Found Solution... (Hope someone finds it useful)

JAVA SCRIPT

function myFunction() {

    var str= "fname=Henry&lname=Ford"; 
    log("MyString=" + str);
}

function log(message) {
    var client = new XMLHttpRequest();
    client.open("POST", "Default.aspx", true);  // Default.aspx being the page being posted to
    client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    client.send(message);
}

C# Default.aspx.cs (CODE BEHIND TO Default.aspx)

protected void Page_Load(object sender, EventArgs e)
{
    getText();
}

public void getText()
{
    if (HttpContext.Current.Request.Form.Keys.Count > 0)
    {
        string code = HttpContext.Current.Request.Form["MyString"];
    // code = "fname=Henry"
    // For looping etc, see below
    }
}

WHAT ELSE YOU CAN GET....

HttpContext.Current.Request.Form.Count       // 2
HttpContext.Current.Request.Form.Keys.Count  // 2

HttpContext.Current.Request.Form.AllKeys[0]  // "MyString"
HttpContext.Current.Request.Form.Keys[0]     // "MyString"
HttpContext.Current.Request.Form.AllKeys[1]  // "lname"
HttpContext.Current.Request.Form.Keys[1]     // "lname"

HttpContext.Current.Request.Form[0]      // "fname=Henry"
HttpContext.Current.Request.Form[1]      // "Ford"

Loop through keys...

foreach (string key in Request.Form.Keys) 
  {
    DoSomething(Request.Form[key]);
  }

Upvotes: 0

kunjee
kunjee

Reputation: 2759

I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?

I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.

Please let me know if any further details needed.

Upvotes: 0

Related Questions