TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Post Multiple JSON Objects to Ajax Method in C#
rizwan khan
Jun 05
2016
Code
10.4
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
C# web method
[System.Web.Services.WebMethod]
public
static
void
Post(
object
data,
object
dt)
{
List < Category > lstItems =
new
JavaScriptSerializer().ConvertToType < List < Category >> (data);
List < Product > lstprditems =
new
JavaScriptSerializer().ConvertToType < List < Product >> (dt);
string
ctid =
""
;
string
ctnme =
""
;
string
pdid =
""
;
string
pdnme =
""
;
for
(
int
i = 0; i < lstItems.Count; i++)
{
ctid = ctid +
","
+ lstItems[i].categoryID;
ctnme = ctnme +
","
+ lstItems[i].categoryName;
}
for
(
int
i = 0; i < lstprditems.Count; i++)
{
pdid = pdid +
","
+ lstprditems[i].productID;
pdnme = pdnme +
","
+ lstprditems[i].productName;
}
if
(ctid.Length > 0)
{
ctid = ctid.Remove(0, 1);
ctnme = ctnme.Remove(0, 1);
}
if
(ctid.Length > 0)
{
pdid = pdid.Remove(0, 1);
pdnme = pdnme.Remove(0, 1);
}
}
Code
<html xmlns=
"http://www.w3.org/1999/xhtml"
>
<head runat=
"server"
>
<script type=
"text/javascript"
src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"
></script>
<script type=
"text/javascript"
>
function PassJavascriptObject()
{
var Ct = [];
var Pd = [];
var categoryModel = {
categoryID: 1,
categoryName:
"Beverage"
};
Ct.push(categoryModel);
var categoryModel1 = {
categoryID: 2,
categoryName:
"Liuwu"
};
Ct.push(categoryModel1);
var productModel = {
productID: 1,
productName:
"Chai"
};
Pd.push(productModel)
var productModel2 = {
productID: 2,
productName:
"teccc"
};
Pd.push(productModel2)
$.ajax(
{
url:
'WebForm1.aspx/Post'
,
type:
'post'
,
dataType:
'json'
,
// It is important to set the content type
// request header to application/json because
// that's how the client will send the request
contentType:
'application/json'
,
data: JSON.stringify(
{
data: Ct,
dt: Pd
}),
cache:
false
,
success: function(result)
{
alert(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
});
}
</script>
</head>
<body>
<form id=
"form1"
runat=
"server"
>
<div>
<span onclick=
"javascript:PassJavascriptObject();"
>Call Method</span>
</div>
</form>
</body>
</html>
JSON Objects
Ajax Method
ASP.NET