asp.net将json发布到控制器

问题描述 投票:1回答:1

当我单击“保存”按钮时,没有任何反应,并且SaveProducts控制器中的断点不响应。为什么?我知道需要实现jsondeserealize,因为产品应该为null。

HomeController.cs

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult SaveProducts(ProductModel product)
    {
        return View("Index");
    }

}

Index.cshtml

@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<div data-bind="with: currentProduct">
<p>Name: <input type="text" data-bind="value: productName" /></p>
</div>
<input type="button" value="Save" data-bind="click: saveProduct" />

<script>

function ProductViewModel() {
    var self = this;
    self.currentProduct = ko.observable(new Product("P1"));
    self.saveProduct = function () {
        var productModel = ko.toJS(self.currentProduct);
        ko.utils.postJson("/Home/SaveProducts", {product: productModel} );
    }
}
function Product(name) {
    var self = this;
    self.productName = ko.observable(name);
}
ko.observable(new ProductViewModel());

</script>

ProductModel.cs

public class ProductModel
{
    public string productName { get; set; }
}
javascript c# json asp.net-mvc knockout.js
1个回答
2
投票

我无法在你的代码中看到你激活你的绑定,我想在这部分你的意思是激活它而不是创建一个可观察的。

ko.observable(new ProductViewModel());

您应该将其更改为:

ko.applyBindings(new ProductViewModel());
© www.soinside.com 2019 - 2024. All rights reserved.