Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass JSON object to Web Method

Tags:

I wanted to shared something I learned today with you all. My question was:

Can you pass a JSON object from JavaScript code to a .NET Page Method? For example:

  var task = { 
    Title: $("#titlenew input", $(newTaskRow)).val(), 
    StartDate: $("#startnew input", $(newTaskRow)).val(), 
    EndDate: $("#endnew input", $(newTaskRow)).val(), 
    EstimatedHours: $("#esthrsnew input", $(newTaskRow)).val(),
    PredecessorsOutlineNumbers: $("#depnew input", $(newTaskRow)).val(),
    OutlineNumber: $("#ordernew", $(newTaskRow)).text()
  };
  PageMethods.AddTask(task, saveNewTaskCompleted, saveNewTaskFailed);

And if you can, what type of .NET object should my web method accept?

I found out that yes, you can pass a JSON object to a Page Method, and it comes across as a Dictionary(Of String, String). So my web method signature looks like this:

<System.Web.Services.WebMethod()> _
Public Shared Sub AddTask(ByVal taskJson As Dictionary(Of String, String))

  Dim oTask As New Task()
  oTask.Title = taskJson("Title")
  ' all other accesses to the JSON object here

End Sub
like image 979
Brandon Montgomery Avatar asked Apr 10 '09 19:04

Brandon Montgomery


1 Answers

Checkout this article: http://dotnetslackers.com/columns/ajax/ASPNETAjaxWebService.aspx

Decorate your WebMethod with [GenerateScriptType(typeof(Task))] then in client side you will be able to create task. then pass it as regular object to your server side method.

like image 56
Kazi Manzur Rashid Avatar answered Oct 12 '22 22:10

Kazi Manzur Rashid