5068

ASP.Net JSON Web Service Post Form Data

Question:

I have a ASP.NET web service decorated with <strong>System.Web.Script.Services.ScriptService()</strong> so it can return json formatted data. This much is working for me, but ASP.Net has a requirement that parameters to the web service must be in json in order to get json out.

I'm using jquery to run my ajax calls and there doesn't seem to be an easy way to create a <em>nice</em> javascript object from the form elements. I have looked at serialiseArray in the json2 library but it doesn't encode the field names as property name in the object.

If you have 2 form elements like this

<input type="text" name="namefirst" id="namefirst" value="John"/> <input type="text" name="namelast" id="namelast" value="Doe"/>

calling <strong>$("form").serialize()</strong> will get you the standard query string

namefirst=John&namelast=Doe

calling <strong>JSON.stringify($("form").serializeArray())</strong> will get you the (bulky) json representation

[{"name":"namefirst","value":"John"},{"name":"namelast","value":"Doe"}]

This will work when passing to the web service but its ugly as you have to have code like this to read it in:

Public Class NameValuePair Public name As String Public value As String End Class <WebMethod()> _ Public Function GetQuote(ByVal nvp As NameValuePair()) As String End Function

You would also have to wrap that json text inside another object nameed nvp to make the web service happy. Then its more work as all you have is an array of NameValuePair when you want an associative array.

I might be kidding myself but i imagined something more elegant when i started this project - more like this

Public Class Person Public namefirst As String Public namelast As String End Class

which would require the json to look something like this:

{"namefirst":"John","namelast":"Doe"}

Is there an easy way to do this? Obviously it is simple for a form with two parameters but when you have a very large form concatenating strings gets ugly. Having nested objects would also complicate things

The cludge I have settled on for the moment is to use the standard name value pair format stuffed inside a json object. This is compact and fast

{"q":"namefirst=John&namelast=Doe"}

then have a web method like this on the server that parses the query string into an associate array.

<WebMethod()> _ Public Function AjaxForm(ByVal q As String) as string Dim params As NameValueCollection = HttpUtility.ParseQueryString(q) 'do stuff return "Hello" End Sub

As far a cludges go this one seems reasonably elegant in terms of amount of code, but my question is: is there a better way? Is there a generally accepted way of passing form data to asp.net web/script services?

Answer1:

You are just having a formatting crisis.

To properly call this code:

Public Class NameValuePair Public name As String Public value As String End Class <WebMethod()> _ Public Function GetQuote(ByVal nvp As NameValuePair()) As String End Function

You need to send a json string that looks like this:

'{"nvp": {"name": "john", "value": "foo"}}'

Do not use jQuery to serialize ScriptService arguments. Use the standard <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="nofollow">json2.js</a>.

Try this: Form

... <input type="text" name="name" id="name" value="John"/> <input type="text" name="value" id="value" value="Foo"/> ...

Script:

var myNvp = {name: $('#name').val(), value:$('#value').val()}; var data = JSON.stringify({nvp: myNvp}); // data is what you post to the service.

I just wrote this off the top of my head but it looks right to me.

Let me know if you have any other questions.

Answer2:

I havn't found anything better than what i was already thinking with passing the serialized string as a parameter.

input:

{"q":"namefirst=John&namelast=Doe"}

webservice:

<WebMethod()> _ Public Function AjaxForm(ByVal q As String) as string Dim params As NameValueCollection = HttpUtility.ParseQueryString(q) 'do stuff return "Hello" End Sub

This seems the cleanest and simplest option

Recommend

  • Pandas read_csv dtype specify all columns but one
  • How do you schedule timed events in Flask?
  • Display ajax response in Table
  • What is a good IDE for Java programming on a low end laptop? [closed]
  • Jquery Array Object - How to add suffix variable to index names
  • How to hide appended input names when the value is empty
  • Console app scheduled task run two different ways
  • Jquery Ajax form using .on(“submit”,
  • Sails.js API passport.js authentication
  • Grunt watch Running “watch” task Waiting
  • Can you use DataSet and DataTables in a Portable Class Library
  • How do I change the kernel/python version for iPython?
  • (Play 2.5) How do you define json format for type alias of an Option?
  • How do I bind multiple properties in an Android layout element
  • Unzip archive in .Net CORE 1.0
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • Select value from xtype selection type checkbox CQ5
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Exception creating JSON with LINQ
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • What's the purpose of QString?
  • How to use carriage return with multiple line?
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • ActiveRecord query for a count of new users by day
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Play WS (2.2.1): post/put large request
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Control modification in presentation layer
  • Different response to non-authenticated users and AJAX calls
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Display Images one by one with next and previous functionality
  • Adding custom controls to a full screen movie
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Confusion with PayPal's monthly billing cycle
  • Circular dependency while pushing http interceptor
  • Linker errors when using intrinsic function via function pointer
  • SQL merge duplicate rows and join values that are different
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Is it possible to post an object from jquery to bottle.py?