Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I send an object from client-side javascript to server-side code via ASP.NET?

Can I send an object from client-side javascript to server-side code via ASP.NET?

like image 905
Badr Avatar asked May 23 '11 05:05

Badr


2 Answers

In ASP.NET WebForms i would use a ScriptService:

Checkout this samples: http://msdn.microsoft.com/en-us/magazine/cc163499.aspx

The GenerateScriptType attribute can used if you wanna pass/get hole objects to the service: ASP.NET ScriptService deserialization problem with derived types

[WebService(Namespace = "http://msdnmagazine.com/ws")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[GenerateScriptType(typeof(Object1))]
[GenerateScriptType(typeof(Object2))]
[ScriptService]
public class StockQuoteService : WebService
{
    static Random _rand = new Random(Environment.TickCount);

    [WebMethod]
    public int GetStockQuote(string symbol)
    {
        return _rand.Next(0, 120);
    }
}
like image 121
benwasd Avatar answered Sep 17 '22 08:09

benwasd


Yes. One way could be, to use a web method; for instance:

  1. Create a service
  2. Call from the JavaScript method like: DataService.Push(yourObject);

For instance:

Javascript methods:

function btnGenerate_onclick(result) {
    DataService.Push(getDataFromSomeDiv(), onGenerateReportComplete /*callback method*/);
    //or
    //DataService.Push(document.getElementById("myDiv").innerHTML, onGenerateReportComplete /*callback method*/);

}

function onGenerateReportComplete(result) {
            alert("Success:" + result);
}

Service methods:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class DataService : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)] //If you want?
    public bool Push(object someObject)
    {
        //var v = someObject as MyObjectClass;//Process object 
        return true;
    }
}

EDIT: How would javascript know what is server-side DataService?

This will require reference of web service in the markup. For instance like following:

<asp:ScriptManager ID="sm" runat="server">
            <Services>
            <asp:ServiceReference Path="DataService.asmx" />
        </Services>
</asp:ScriptManager>

Or you can use callbacks/page methods.

like image 26
KMån Avatar answered Sep 18 '22 08:09

KMån