How do pass a JavaScript object into ASP.NET Handler and parse the values?
I have created an Complex type object like:
function AccountObjCreate() {
var AccountsView = {};
AccountsView.Username = null;
AccountsView.Email = null;
AccountsView.Password = null;
return AccountsView;
}
And fill that object like:
var aView = AccountObjCreate();
aView.Username = $('#tbUserName').val().trim();
aView.Email = $('#tbEmail').val().trim().toLowerCase();
aView.Password = $('#tbPassword').val().trim();
Then I am calling:
$.post("/Handlers/AccountHandler.ashx", { obj: aView },
function (results) {
if (results.isSuccess) {
alert(results.msg);
} else {
alert(results.msg);
}
}, "json");
When I view it in the console I see all my data within aView as json.
My ASP.NET Handler page is
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
string obj = context.Request["obj"];
But the obj is NULL.
In order to get the object through to the server you should serialize it into a string (you could use the method described here or include the JSON library for javascript here) and then deserialize it using the .NET
JavaScriptSerializerclass.JS code.
Then on the server handler you can parse the JSON string with the mentioned
JavaScriptSerializerclass.