我有 javascript getter setter 类
function UserContext() {
var category_id;
var biller_id;
this.get_category_id = function () {
return category_id;
}
this.set_category_id = function (value) {
category_id = value;
}
this.get_biller_id = function () {
return biller_id;
}
this.set_biller_id = function (value) {
biller_id = value;
}
}
我在jquery
点击事件中创建这个类的对象
var contextObj = new UserContext();
contextObj.set_category_id('SOME VALUE');
contextObj.set_biller_id('65');
我在c#中有类似的类(class)
public class CustomerDTO
{
public string category_id { get; set; }
public string biller_id{ get; set; }
}
还有一个asp:hidden
元素
<asp:HiddenField ID="hdnValue" ClientIDMode="Static" runat="server" />
我想要实现的目标
- 通过序列化的方式将
contextObj
赋给asp:hidden
元素(可以是json格式) - 在 Code behind 中获取此对象,将其脱轨并将值分配给其各自的 c# 类,即
CustomerDTO
- 这样我就可以通过所有页面请求访问所有这些值(通过在 Server.Transfer 请求中传递此对象)
为了序列化对象,我尝试了这个
console.log(JSON.stringify(contextObj));
但它什么也不打印。我想要打印值,以便我可以分配给隐藏变量
最佳答案
你的语法错误。问题是您的变量是私有(private)的,stringify() 函数无法访问它们。事实上,如果您尝试直接访问私有(private)变量,您将得到“未定义”。
序列化仅适用于公共(public)成员,这是有道理的,因为私有(private)变量不可访问。
这应该是一个快速的 hack,但它会使您的变量公开(只要您使用 this.category_id = value),因此它破坏了封装,这并不好:
function UserContext() {
this.category_id;
this.biller_id;
this.get_category_id = function() {
return this.category_id;
}
this.set_category_id = function(value) {
this.category_id = value;
}
this.get_biller_id = function() {
return this.biller_id;
}
this.set_biller_id = function(value) {
this.biller_id = value;
}
}
var contextObj = new UserContext();
contextObj.set_category_id('SOME VALUE');
contextObj.set_biller_id('65');
alert(JSON.stringify(contextObj));
function UserContext() {
var category_id;
var biller_id;
this.get_category_id = function() {
return category_id;
}
this.set_category_id = function(value) {
category_id = value;
}
this.get_biller_id = function() {
return biller_id;
}
this.set_biller_id = function(value) {
biller_id = value;
}
this.toJSON = function() {
return {
"category_id": category_id,
"biller_id": biller_id
};
};
}
var contextObj = new UserContext();
contextObj.set_category_id('SOME VALUE');
contextObj.set_biller_id('65');
alert(JSON.stringify(contextObj));
因此,您的变量只能通过您的 setter 和 getter 访问,并且您还可以使用您的私有(private)成员序列化您的对象!我会称之为双赢局面!
关于javascript - 序列化javascript对象并反序列化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054570/