asp.net 将 JSON 发布到控制器
本文关键字:控制器 JSON net asp | 更新日期: 2023-09-27 18:34:50
当我单击"保存"按钮时,没有任何反应,保存产品控制器中的断点没有响应。为什么?我知道需要实现 jsondesereal,因为产品应该是空的。
首页控制器.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>
产品型号.cs
public class ProductModel
{
public string productName { get; set; }
}
我在您的代码中看不到您在哪里激活了绑定,我认为在这一部分中,您的意思是激活它而不是创建可观察量。
ko.observable(new ProductViewModel());
您应该将其更改为:
ko.applyBindings(new ProductViewModel());