如何使用Razor模型中的数据更新Knockout视图模型?我的Razor页面是从.NET Core MVC项目中的简单GET Action生成的。简单的观点是:
@model Birder2.ViewModels.SalesOrderViewModel
@using Newtonsoft.Json
@{ string data = JsonConvert.SerializeObject(Model); }
<script src="~/js/salesorderviewmodel.js"></script>
<script type='text/javascript' src="~/js/knockout-3.4.2.js"></script>
<script type='text/javascript'>
var salesOrderViewModel = new SalesOrderViewModel(@Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
</script>
<p data-bind="text: MessageToClient"></p>
<div>
<div>
<label>Customer Name</label>
<span data-bind="text: CustomerName"></span>
</div>
<div>
<label>PO No.</label>
<span data-bind="text: PONumber"></span>
</div>
我有以下Knockout视图模型,如上所述:
SalesOrderItemViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
控制器在这里:
public async Task<IActionResult> Details(int? id)
SalesOrderViewModel salesOrderViewModel = new SalesOrderViewModel()
{
SalesOrderId = salesOrder.SalesOrderId,
CustomerName = salesOrder.CustomerName,
PONumber = salesOrder.PONumber
};
salesOrderViewModel.MessageToClient = "I originated from the viewmodel, rather than the model.";
return View(salesOrderViewModel);
我对Knockout很新。遗憾的是,我找不到任何特定于.NET Core的有效文档。问题似乎是更新Knockout视图模型。该视图使用空数据字段呈现。
任何人都可以帮助确定问题吗?
答案 0 :(得分:1)
一切看起来都很正确。您唯一应该尝试的是将您的脚本与html 下的ko.applyBindings(salesOrderViewModel)
放置在数据库中
或者,您可以使用window.onload
:
window.onload = function() {
var salesOrderViewModel = new SalesOrderViewModel(@Html.Raw(data));
ko.applyBindings(salesOrderViewModel);
};