With the below javascript code i am trying some BackboneJs concepts. Couldn’t figure out why the response after invoking a XHR request is HTML of full page rather than the serialized version of Person class. Have a look below
Server Side Code is of C# and ASP.NET 2.0
note: forget the urland urlroot on the model, i am using the backbonejs Sync
Javascript
window.Person = Backbone.Model.extend({
defaults: {
id: Math.random(),
name: "Type your name"
},
initialize: function (model) {
this.bind("change", this.ModelChanged);
},
ModelChanged: function () {
},
url: "CreatePerson",
urlRoot: "/index.aspx/"
});
Backbone.sync = function (met, mod, op) {
switch (met) {
case "create":
break;
case "update":
break;
case "delete":
break;
case "read":
break;
default:
break;
}
};
Server side code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Person CreatePerson(Person newPerson)
{
List<Person> peopleList = HttpContext.Current.Session["People"] as List<Person>;
if (peopleList == null)
{
peopleList = new List<Person>();
}
Person p1 = new Person();
p1 = newPerson;
peopleList.Add(p1);
HttpContext.Current.Session["People"] = peopleList;
return p1;
}
Person class
public class Person
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
Finally the test code
var x = new Person({
name: "StackOverflow"
});
$.post("index.aspx/CreatePerson", "{" + JSON.stringify(x) + "}", function () {
console.log(arguments)
});
I don’t understand why but jQuery made me follow this weird procedure to get this done.
It serializes valid json to URL encoded format & not json string which is wrong.