Can I send an object from client-side javascript to server-side code via ASP.NET?
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);
}
}
Yes. One way could be, to use a web method; for instance:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With