5

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
asked Apr 10, 2009 at 19:27
4
  • This is a Q&A site, not a blog. Commented Apr 10, 2009 at 19:33
  • From the FAQ for stackoverflow: "It's also perfectly fine to ask and answer your own programming question, but pretend you're on Jeopardy: phrase it in the form of a question." You've not done this. Maybe rewrite it as question/answer. Commented Apr 10, 2009 at 19:48
  • My bad - should I ask the question and then post the answer separately? Commented Apr 10, 2009 at 20:51
  • You shouldn't have done it, perhaps, but I am glad you did... Commented Sep 18, 2011 at 21:15

2 Answers 2

5

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.

answered Apr 11, 2009 at 12:19

Comments

0

A detailed answer for a similar question states that combining the JQuery & Json2.stringfy() can be used for sending complex type to Server-Side methods.

And on the Server Side, you will only need to put the required Type in the Method Signature

(ex. foo(MyType obj) { ... } )

How to send JSON object to asp.net web service and process the data there?

answered Feb 13, 2013 at 7:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.