简体   繁体   English

Javascript对象传递给ASP.NET Handler

[英]Javascript Object pass to ASP.NET Handler

How do pass a JavaScript object into ASP.NET Handler and parse the values? 如何将JavaScript对象传递给ASP.NET Handler并解析值?

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. 当我在控制台中查看它时,我将aView中的所有数据视为json。

My ASP.NET Handler page is 我的ASP.NET处理程序页面是

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
string obj = context.Request["obj"];

But the obj is NULL. 但是obj是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 JavaScriptSerializer class. 为了通过你应该序列化到一个字符串的服务器来获取对象(可以使用所描述的方法在这里或包括JSON JavaScript库在这里 ),然后使用.NET反序列化JavaScriptSerializer类。

JS code. 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");​

Then on the server handler you can parse the JSON string with the mentioned JavaScriptSerializer class. 然后在服务器处理程序上,您可以使用提到的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;
}

jQuery doesn't automatically stringify objects for you. jQuery不会为您自动为对象字符串化。 You have to do it yourself. 你必须自己做。

Download this: https://github.com/douglascrockford/JSON-js 下载: https//github.com/douglascrockford/JSON-js

Add the script reference to your HTML and change your $.post call to: 将脚本引用添加到HTML并将$.post调用更改为:

$.post("/Handlers/AccountHandler.ashx", { obj: JSON.stringify(aView, null, 2) }...

Also the ContentType is incorrect. ContentType也不正确。 I'd just leave it as the default. 我只是把它作为默认值。 While you will be submitting JSON data in this manner the ContentType itself is not JSON. 虽然您将以这种方式提交JSON数据,但ContentType本身不是JSON。 The content type is going to be regular post data. 内容类型将是常规的帖子数据。 This is post data: 这是发布数据:

obj={"Username":"MyUsername", "Password":"MyPassword"...

this is JSON 这是JSON

{"obj":{"Username":"MyUsername", "Password":"MyPassword"...

It can get kind of confusing sometimes. 有时会让人感到困惑。

A better approach would be to look into ASP.Net MVC. 更好的方法是研究ASP.Net MVC。 The Controller Methods are able to automatically deserialize JSON objects into .Net models so you can do this on your client side code: Controller方法能够自动将JSON对象反序列化为.Net模型,因此您可以在客户端代码上执行此操作:

$.post("/Handlers/AccountHandler.ashx", JSON.stringify({ view: aView }, null, 2) }...

Write a .Net class that matches aView's structure: 编写一个与aView结构匹配的.Net类:

class Account { 
    public string Username { get; set; } 
    public string Password { get; set; }
    public string Email { get; set; }
}

And then define a controller method like so: 然后定义一个控制器方法,如下所示:

public JsonResult SaveAccount(Account view)

Makes things a lot simpler. 使事情变得简单得多。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM