Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Bounty
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Post Multiple JSON Objects to Ajax Method in C#
WhatsApp
rizwan khan
Jun 05
2016
10.6
k
0
0
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
Up Next
Post Multiple JSON Objects to Ajax Method in C#