webform ajax json,jquery - ASP.Net JSON Web Service Post Form Data - Stack Overflow

I have a ASP.NET web service decorated with System.Web.Script.Services.ScriptService() 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 nice 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

calling $("form").serialize() will get you the standard query string

namefirst=John&namelast=Doe

calling JSON.stringify($("form").serializeArray()) 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

_

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.

_

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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值