POST KnockoutJS data to mvc controller not binding

I'm trying to do a post of the mapped KnockoutJS model. I can see when debugging it, the JSON is correct. But the server shows that Product is 0 (empty). While it does contain 1 item.

MVC Controller:

[HttpPost]
public ActionResult Test(MyModel model, FormCollection fc)
{
   return RedirectToAction("index");
}

The AJAX submit:

$('#btnSubmit').click(function (event) {
        var theModel = ko.mapping.toJSON(viewModel);
        debugger;
        $.ajax({
            type: 'POST',
            url: "@Url.Action("Test", "Home")",
            data: theModel,
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                if (!result.success) {
                    //alert(result.error);
                }
                else { }
            }
        });
    });

This is a partial JSON object:

"Products":[{"Id":2,"Name":"bread"}]

What am I doing wrong?

EDIT:

public class MyModel
{
   public int User { get; set; }
   public string Address { get; set; }
   public string ZipCode { get; set; }
   public List<Product> Products { get; set; }

}

public class Product
{
   public int Id { get; set; }
   public string Name { get; set; } 
}

Answers


Here is a full working tested example (sending a model back from the controller and posting):

Controller

public ActionResult Test()
{
    var model = new MyModel();
    model.Products = new List<Product> { new Product { Id = 2, Name = "bread" } };
    return View(model);
}

[HttpPost]
public ActionResult Test(MyModel model, FormCollection fc)
{
    // Count equals one
    var count = model.Products.Count();
    return RedirectToAction("index");
}

Model

public class MyModel
{
    public int User { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public List<Product> Products { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

View

@model MyModel
<form method="post">
    <input id="btnSubmit" type="submit" value="submit" />
</form>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">

    var Product = function (Id, Name) {
        self = this;
        self.Id = Id;
        self.Name = Name;
    }

    var mapping = {
        'Products': {
            create: function (options) {
                return new Product(options.data.Id, options.data.Name);
            }
        }
    }


    function MyModel(data) {
        var self = this;
        ko.mapping.fromJS(data, mapping, self);
    }

    var viewModel = new MyModel(@Html.Raw(Json.Encode(Model)));

    $('#btnSubmit').click(function (event) {
        event.preventDefault();
        var theModel = ko.mapping.toJSON(viewModel);
        debugger;
        $.ajax({
            type: 'POST',
            url: "@Url.Action("Test", "Home")",
            data: theModel,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (result) {
                if (!result.success) {
                    //alert(result.error);
                }
                else { }
            }
        });
    });

    </script>

Need Your Help

ErrorDocument 404 Not Sending Referrer Information: PHP

php .htaccess http-status-code-404 referrer errordocument

I'm using a standard htaccess ErrorDocument 404 to redirect users to a new page. In order to customize the 404, I need to know their referrer information (from the page they Tried to visit).

Migrating to FuelPHP with existing database

php codeigniter orm fuelphp

I'm migreting from Codeigniter to FuelPHP. I like Fuel's ORM and other nice stuff and it's really good to enough to start with if you're creating an app from scratch. In my case I have a populated ...