0

我正在开发一个相对简单的 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。提前致谢!

4

2 回答 2

0

您使用了 knockout.mapping 插件,但我没有看到您包含映射插件 js 文件。您需要在敲除 lib 文件之后包含它:https ://github.com/SteveSanderson/knockout.mapping/tree/master/build/output 。

此外,您的匿名函数永远不会运行。要立即调用它,您需要用括号结束它,如下所示:

(function () {
    var model = '@Html.Raw(Json.Encode(Model))';
       var viewModel = ko.mapping.fromJS(model);
       ko.applyBindings(viewModel);

})();
于 2013-06-18T19:59:41.400 回答
0

我建议您查看一个名为Shoelace的开源项目

就像@lagerone在他的帖子中描述的将MVC 模型映射到Knockout模型(因此您不必维护两个模型定义)一样,我用不同的模式做得很好。

UserList.chtml(MVC 视图)

@Html.PartialResource(@<script src="@Url.Content("~/Scripts/app/Views/Account/userlist.viewmodel.js")" type="text/javascript"></script>, "js")
@Html.PartialResource(
@<script type="text/javascript">
     $(function () {
         var viewModelObj = APP.userListViewModel(ko.mapping.fromJS(@Html.Raw(Model.ToJson())));
            ko.applyBindings(viewModelObj, document.getElementById("cntnrUserList"));
        });

    </script>, "js")

但是,我的模式将模型传递给 ViewModel 对象以扩展 if 以进行验证、复杂的可观察对象、事件函数定义等。

userListViewModel (javascript 类)

APP.userListViewModel = function (model) {
    var self = model;
    $.extend(APP.manageProfileViewModel, model);
    self.selectedUser = ko.observable({});
    self.confirmDelete = function () {
        $("#hdDeleteUserId").val(this.userId());
    };
    self.performDelete = function () {
        //alert("performDelete called for UserId: " + $("#hdDeleteUserId").val());
        var url = APP.helpers.prepareRelativeUrl("Account/DeleteUser");
        APP.helpers.performAjaxPost(url,
                JSON.stringify({ UserId: $("#hdDeleteUserId").val() }),
                function (result) {
                    if (result != null && result.success == true) {
                        alert('Your profile has been update.');
                        location.reload();
                    }
                },
                function () {
                    alert('An error has occured. Please try again.');
                });
    };
    self.cancel = function () {
        //alert("cancelDelete called");
    };
    self.showUserPermissions = function () {
        self.selectedUser(this);
        //$("#hdPermissionsUserId").val(this.userId());
    };
    self.saveUserPermissions = function () {
        var url = APP.helpers.prepareRelativeUrl("Account/SaveUserRoles");
        APP.helpers.performAjaxPost(url,
                ko.toJSON(self.selectedUser),
                function (result) {
                    //Do nothing.
                },
                function () {
                    alert('An error has occured. Please try again.');
                });
    };
    return ko.validatedObservable(self);
};

鞋带采用以下位:

于 2013-10-03T15:40:30.340 回答