I am having some problems Posting my Javascript Array of objects to C# Codebehind. I followed a simple tutorial and thought this would work quite nicely but my C# codebehind breakpoints in PassThings
is never hit.
I have tried changing the url to "Default.aspx/PassThings" but it still never gets posted to my code behind, the error alert displays "[object object"]
Here is my client side:
Default.aspx
Script
<script>
function Save() {
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/PassThings',
data: things,
success: function () {
alert("success");
},
error: function (response) {
alert(response);
}
});
});
}
</script>
Html
<input type="button" value="Pass Things" onclick="JavaScript: Save();">
Default.aspx.cs
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
}
Does anyone see what I am doing wrong?
Thank you for your time.
In url
pass proper url with page. Suppose the PassThings
method is in Default.aspx
page code behind file then you have to pass url: Default.aspx/PassThings if the script code is written within the Default.aspx.
If script in seperate js file which is in Scripts folder, then you have to come back one directory and have to write : url: ../Default.aspx/PassThings
$(document).ready(function () {
var things = [{
id: 1,
color: 'yellow'
}, {
id: 2,
color: 'blue'
}, {
id: 3,
color: 'red'
}];
things = JSON.stringify({
'things': things
});
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'Default.aspx/PassThings',
data: things,
success: function () {
alert("success");
},
error: function (response) {
alert(JSON.stringify(response));
}
});
});
and in code behind your method should be decorated with [WebMethod]
and it should be public
and static
:
[WebMethod]
public static void PassThings(List<Thing> things)
{
var t = things;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments