Why is DataContractJsonSerializer not serializing my Id property?

I am using LINQ-to-SQL for CRUD functions and DataContractJsonSerializer

for serializing an object to JSON. I am also using ASP.NET MVC data binding to post values ​​for an MVC action that does the insert. The problem is that it will serialize all properties except the Id property. I have a model set up like this:

[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 */
}

      

Here's my custom one 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);
    }
}

      

Here's the action (JsonContract () returns a 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
     }

      

The only thing I can think of is that some data binding is preventing the Id property from being serialized since it was populated after it was deserialized from the form data. Any suggestions?

+2


source to share


1 answer


What does the normal Json () method return for this object?

As per this post ... there might be a problem with auto backup fields in C #:



http://aaron-powell.spaces.live.com/blog/cns!91A824220E2BF369!150.entry

+1


source







All Articles