views:

271

answers:

1

I'm using LINQ-to-SQL for CRUD functionality, and DataContractJsonSerializer to serialize the object to JSON. I am also using ASP.NET MVC's data binding to post values to an MVC action that does the inserting. The problem is that it will serialize all of the properties except the Id property. I've got the model set up as so:

[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 is my custom 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 somehow data binding is preventing the Id property from being serialized because it was populated after it was deserialized from the form data. Any suggestions?

A: 

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

According to this post... there might be an issue with the automatic backing fields in C#:

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

Jeremy Bell