我正在开发一个相对简单的 Web 应用程序,我的主管建议我结合使用 Knockout、MVC 和 Bootstrap 来完成我的任务。不幸的是,我被困在可能是项目中微不足道的部分上。
我已经看过很多 Knockout 教程,并且一直在尝试模仿他们最简单的教程,在这里可以找到: http ://learn.knockoutjs.com/#/?tutorial=intro
不幸的是,我的数据绑定似乎都不起作用。可观察对象永远不会保留其分配的值。
我在搜索时也遇到了这个线程,并试图模仿它,但无济于事。基本上,我只想知道如何在 Visual Studio MVC4 中正确实现 Knockout 数据绑定。这是我的 HTML 代码,其中很多是我从上面提到的线程中抄袭而来的。
@model FluidBedSimulation.Models.BedState
@using Newtonsoft.Json
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@if (false)
{
<script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.2.0.js" type="text/javascript"></script>
}
<script src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-2.2.0.js")" type="text/javascript"></script>
<script type="text/javascript">
this.BedMass = ko.observable(1);
this.BedWaterMass = ko.observable(1);
this.binderFraction = ko.observable(1);
(function () {
var model = '@Html.Raw(Json.Encode(Model))';
var viewModel = ko.mapping.fromJS(model);
ko.applyBindings(viewModel);
});
</script>
@*grab values from the view model directly*@
<p>Bed Weight: <strong data-bind="text: BedMass" id="BedMass"></strong></p>
<p>H2O Bed Weight: <strong data-bind="text: BedWaterMass" id="BedWaterMass"></strong></p>
<p>Fraction of Binder in Spray Solution: <strong data-bind="text: binderFraction" id="binderFraction"></strong></p>
<p>
Enter the Bed Mass:
<input data-bind="value: BedMass" />
@*Html.TextBoxFor(model => model.BedMass, new { data_bind = "value: BedMass" })*@
</p>
<p>
Enter the H2O Mass in the Bed:
@Html.TextBoxFor(model => model.BedWaterMass, new { data_bind = "value: BedWaterMass" })
</p>
<p>
Enter the Fraction of Binder in the Spray Solution:
@Html.TextBoxFor(model => model.binderFraction, new { data_bind = "value: binderFraction" })
</p>
<button data-bind="click: Simulate">Simulate</button>
这是我的简单模型...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FluidBedSimulation.Models
{
public class BedState
{
public double BedMass { get; set; }
public double BedWaterMass { get; set; }
public int binderFraction { get; set; }
public double EvapRate { get; set; }
public double SprayRate { get; set; }
public double AirTemp { get; set; }
public double AirFlow { get; set; }
}
}
和简单的控制器。没有什么花哨。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FluidBedSimulation.Models;
using Newtonsoft.Json;
namespace FluidBedSimulation.Controllers
{
public class SimulationController : Controller
{
//
// GET: /Simulation/
public ActionResult Index()
{
BedState state = new BedState
{
BedMass = 0,
BedWaterMass = 0,
binderFraction = 0,
AirFlow = 0,
AirTemp = 0,
EvapRate = 0,
SprayRate = 0
};
FluidBed bed = new FluidBed
{
FluidBedStates = new List<BedState> { state }
};
return View(state);
}
}
}
如果你们能让我开始做这件事,我将不胜感激。否则我可能只需要坚持使用好的 ol' JQuery 和 html。提前致谢!