質問

I am using MVC 4 and have been struggling with getting Json from the client constructed by Knockout.Js back to my Controller Action. The Json gets posted ok and examining it in Fiddler all seems fine but when the JsonResults Action binds it the object produced doesn't have an ICollection that was present in the Json.

My Client ajax post looks like this:

$.ajax({
            url: location.href,
            type: 'POST',
            data: ko.toJSON(this.Orders),
            dataType: "json",
            contentType: "application/json charset=utf-8",
            success: function (data) {
                alert(data.Message);
            }
        });

That produces the following Json:

[{"Number":1,"Properties":{"Id":2,"Title":"#333"},"UnitCost":"20"}]

My viewModel structure on the server side is so:

Order model

     public class VmOrder 

{

    public int Number
    {
        get;
        set;
    }

    public ICollection<VmProperty> Properties
    {
        get;
        set;
    }

    public decimal UnitCost
    {
        get;
        set;
    }

 }  

Property model

   public class VmProperty
    {

    public int Id
    {
        get;
        set;
    }

    public string Title
    {
        get;
        set;
    }
 }

And lastly my Controller looks like this:

    [HttpPost]
    public JsonResult Order(ICollection<VmOrder> Orders)
    {

        // further server-side validation, save to database, etc
        return Json("Saved", "");
    }

Although i get the Number and UnitCost the Properties collection is null, any ideas?

役に立ちましたか?

解決 2

As Nemsev said, "Properties":{"Id":2,"Title":"#333"} contains just an object and not an array. The array version would look like: "Properties":[{"Id":2,"Title":"#333"}]. So on the C# side you need public VmProperty Properties { get; set; } instead of the collection.

他のヒント

Try replacing:

contentType: "application/json charset=utf-8"

with:

contentType: "application/json; charset=utf-8"

You were missing a ; and thus resulting in an invalid and non-existent Content-Type request header.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top