javascript - POST KnockoutJS data to mvc controller not binding - Stack Overflow

I'm trying to do a post of the mapped KnockoutJS model. I can see when debugging it, the JSON is c

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; } 
}

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; } 
}
Share Improve this question edited Dec 9, 2013 at 18:22 Quoter asked Dec 9, 2013 at 16:15 QuoterQuoter 4,30214 gold badges52 silver badges71 bronze badges 7
  • Could you post MyModel ? – Joffrey Kern Commented Dec 9, 2013 at 16:31
  • we use ko.dataFor stackoverflow./questions/14968565/… – Matt Bodily Commented Dec 9, 2013 at 16:35
  • @JoffreyKern, MyModel added – Quoter Commented Dec 9, 2013 at 16:56
  • As we can see your Product has no notion of TypeId. It has a property of Id. But, the JSON you have posted contains a TypeId – Shuhel Ahmed Commented Dec 9, 2013 at 17:13
  • Try fixing you javascirpt model that represents Product. Replace TypeId with Id or the vice versa. – Shuhel Ahmed Commented Dec 9, 2013 at 17:20
 |  Show 2 more ments

2 Answers 2

Reset to default 3

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>

After investigating some more with fiddler, it turned out that I was getting a 500 error with this message:

System.MissingMethodException: No parameterless constructor defined for this object.

After adding the parameterless constructor in the model, I still got the error message. This was caused because I had a few SelectList in my model. So that's why It couldn't be bound to the model.

Found the solution on this SO post (look for the answer of Chris S). Hope it helps others when facing this issue too.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744994652a4605116.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信