Rav*_*Ram 2 javascript c# asp.net json httphandler
如何将JavaScript对象传递给ASP.NET Handler并解析值?
我创建了一个复杂类型对象,如:
function AccountObjCreate() {
var AccountsView = {};
AccountsView.Username = null;
AccountsView.Email = null;
AccountsView.Password = null;
return AccountsView;
}
Run Code Online (Sandbox Code Playgroud)
并填写该对象,如:
var aView = AccountObjCreate();
aView.Username = $('#tbUserName').val().trim();
aView.Email = $('#tbEmail').val().trim().toLowerCase();
aView.Password = $('#tbPassword').val().trim();
Run Code Online (Sandbox Code Playgroud)
然后我打电话给:
$.post("/Handlers/AccountHandler.ashx", { obj: aView },
function (results) {
if (results.isSuccess) {
alert(results.msg);
} else {
alert(results.msg);
}
}, "json");
Run Code Online (Sandbox Code Playgroud)
当我在控制台中查看它时,我将aView中的所有数据视为json.
我的ASP.NET处理程序页面是
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
string obj = context.Request["obj"];
Run Code Online (Sandbox Code Playgroud)
但是obj是NULL.
为了通过你应该序列化到一个字符串的服务器来获取对象(可以使用所描述的方法在这里或包括JSON JavaScript库在这里),然后使用.NET反序列化JavaScriptSerializer类.
JS代码.
var data = {
obj: JSON.stringify(aView)
};
$.post("/Handlers/AccountHandler.ashx", data, function(results) {
if (results.isSuccess) {
alert(results.msg);
} else {
alert(results.msg);
}
}, "json");?
Run Code Online (Sandbox Code Playgroud)
然后在服务器处理程序上,您可以使用提到的JavaScriptSerializer类解析JSON字符串.
public class AccountsView {
public string Username;
public string Email;
public string Password;
}
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string value = context.Request["obj"];
var aView = serializer.Deserialize(value, typeof(AccountsView));
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8323 次 |
| 最近记录: |