gpt4 book ai didi

asp.net-mvc - 为什么 DataContractJsonSerializer 不序列化我的 Id 属性?

转载 作者:行者123 更新时间:2023-12-02 04:18:23 25 4
gpt4 key购买 nike

我将 LINQ-to-SQL 用于 CRUD 功能,并且 DataContractJsonSerializer将对象序列化为 JSON。我还使用 ASP.NET MVC 的数据绑定(bind)将值发布到执行插入的 MVC 操作。问题是它将序列化除 Id 属性之外的所有属性。我已经将模型设置为:

[Serializable]
[DataContract(Name = "campaign")]
[Table(Name = "hl.campaigns")]
public class Campaign
{
[DataMember(Name = "id")]
[Column(Name = "id", AutoSync = AutoSync.OnInsert, IsDbGenerated = true, IsPrimaryKey = true)]
public Int32 Id { get; set; }

[DataMember(Name = "createdBy")]
[Column(Name = "created_by")]
public Int32 CreatedBy { get; set; }

[DataMember(Name = "createdOnUtc")]
[Column(Name = "created_on_utc")]
public DateTime CreatedOnUtc { get; set; }

[DataMember(Name = "name")]
[Column(Name = "name", DbType = "NVarChar(256)")]
public String Name { get; set; }

/* more properties here */
}

这是我的自定义 JsonDataContractActionResult :
public class JsonDataContractActionResult : ActionResult
{
public JsonDataContractActionResult(Object data)
{
this.Data = data;
}

public Object Data { get; private set; }

public override void ExecuteResult(ControllerContext context)
{
var serializer = new DataContractJsonSerializer(this.Data.GetType());
String output = String.Empty;
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, this.Data);
output = Encoding.Default.GetString(ms.ToArray());
}
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(output);
}
}

这是操作(JsonContract() 返回 JsonDataContractActionResult ):
    [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Modify([Bind(Prefix = "campaign")] Campaign campaign)
{
if (campaign.Id == 0)
{
try
{
CoreDB.Campaigns.InsertOnSubmit(campaign);
CoreDB.SubmitChanges();

return JsonContract(campaign);
}
catch(Exception ex)
{
// TODO: error handling
}
}
return null; // TODO: modification
}

我唯一能想到的是,数据绑定(bind)以某种方式阻止了 Id 属性的序列化,因为它是在从表单数据反序列化后填充的。有什么建议么?

最佳答案

这个对象的常规 Json() 方法返回什么?
根据这篇文章... C# 中的自动支持字段可能存在问题:
http://aaron-powell.spaces.live.com/blog/cns!91A824220E2BF369!150.entry

关于asp.net-mvc - 为什么 DataContractJsonSerializer 不序列化我的 Id 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com