如何在ASP.NET MVC ViewModels中使用knockout.js?

cho*_*bo2 128 asp.net-mvc asp.net-mvc-3 knockout.js

赏金

已经有一段时间了,我还有几个悬而未决的问题.我希望通过添加赏金,这些问题可能会得到解答.

  1. 你如何使用knockout.js的html助手
  2. 为什么需要文档才能使其正常工作(有关详细信息,请参阅第一次编辑)

  3. 如果我使用我的视图模型的淘汰映射,我该如何做这样的事情?由于映射我没有功能.

    function AppViewModel() {
    
        // ... leave firstName, lastName, and fullName unchanged here ...
    
        this.capitalizeLastName = function() {
    
        var currentVal = this.lastName();        // Read the current value
    
        this.lastName(currentVal.toUpperCase()); // Write back a modified value
    
    };
    
    Run Code Online (Sandbox Code Playgroud)
  4. 我想使用插件,例如我希望能够回滚observable,就好像用户取消我希望能够返回到最后一个值的请求一样.根据我的研究,这似乎可以通过人们制作像可编辑的插件来实现的

    如果我使用映射,我该如何使用类似的东西?我真的不想去一个方法,我在我的视图中手动映射我将每个MVC viewMode字段映射到KO模型字段,因为我想尽可能少的内联javascript,这似乎是工作的两倍,那是为什么我喜欢那个映射.

  5. 我担心为了使这项工作变得简单(通过使用映射),我将失去很多KO能力,但另一方面,我担心手动映射只会是很多工作,并会使我的观点包含太多信息和可能会在将来变得难以维护(例如,如果我删除MVC模型中的属性,我也必须在KO视图模型中移动它)


原帖

我正在使用asp.net mvc 3而且我正在寻找淘汰赛因为它看起来很酷但我很难弄清楚它是如何与asp.net mvc特别是视图模型一起工作的.

对我来说,我现在做这样的事情

 public class CourseVM
    {
        public int CourseId { get; set; }
        [Required(ErrorMessage = "Course name is required")]
        [StringLength(40, ErrorMessage = "Course name cannot be this long.")]
        public string CourseName{ get; set; }


        public List<StudentVm> StudentViewModels { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我会有一个Vm,它有一些基本的属性,比如CourseName,它会有一些简单的验证.如果需要,Vm模型也可以包含其他视图模型.

然后,我会将此Vm传递给View,我会使用html帮助程序来帮助我将其显示给用户.

@Html.TextBoxFor(x => x.CourseName)
Run Code Online (Sandbox Code Playgroud)

我可能会有一些foreach循环或某些东西来从Student View Models集合中获取数据.

然后,当我提交表单时,我将使用jquery并将serialize array其发送到控制器操作方法,该方法将其绑定回viewmodel.

使用knockout.js它是完全不同的,因为你现在有了它的视图模型,从我看到的所有例子他们不使用html助手.

你如何使用MVC与knockout.js的这两个功能?

我发现这个视频及其简短(视频@ 18:48的最后几分钟)通过基本上具有内联脚本的方式来使用视图模型,该脚本具有在ViewModel中分配值的knockout.js视图模型.

这是唯一的方法吗?在我的例子里有一个viewmodels集合怎么样?我是否必须使用foreach循环或其他东西来提取所有值并将其分配到淘汰赛中?

至于html助手,视频没有说明他们.

这两个区域让我感到困惑,因为没有多少人似乎在谈论它,这让我对初始值和所有内容如何进入视图感到困惑,而实例只是一些硬编码的值示例.


编辑

我正在尝试Darin Dimitrov所建议的,这似乎有效(我不得不对他的代码进行一些更改).不知道为什么我必须使用文件准备但不知何故没有它就没有准备好.

@model MvcApplication1.Models.Test

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
    <script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
   <script type="text/javascript">

   $(function()
   {
      var model = @Html.Raw(Json.Encode(Model));


// Activates knockout.js
ko.applyBindings(model);
   });

</script>

</head>
<body>
    <div>
        <p>First name: <strong data-bind="text: FirstName"></strong></p>
        <p>Last name: <strong data-bind="text: LastName"></strong></p>
        @Model.FirstName , @Model.LastName
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我不得不把它包装在一个jquery文件中,准备好让它工作.

我也得到了这个警告.不确定它是什么.

Warning 1   Conditional compilation is turned off   -> @Html.Raw
Run Code Online (Sandbox Code Playgroud)

所以我有一个起点我想至少会更新,当我做了一些更多的游戏,以及它是如何工作的.

我正在尝试浏览交互式教程,但使用的是ViewModel.

不知道如何处理这些部件

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}
Run Code Online (Sandbox Code Playgroud)

要么

function AppViewModel() {
    // ... leave firstName, lastName, and fullName unchanged here ...

    this.capitalizeLastName = function() {
        var currentVal = this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase()); // Write back a modified value
    };
Run Code Online (Sandbox Code Playgroud)


编辑2

我找到了第一个问题.没有关于第二个问题的线索.但是.有人有任何想法吗?

 @model MvcApplication1.Models.Test

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <html>
    <head>
        <title>Index</title>
        <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
        <script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
        <script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
       <script type="text/javascript">

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

       });

    </script>

    </head>
    <body>
        <div>
            @*grab values from the view model directly*@
            <p>First name: <strong data-bind="text: FirstName"></strong></p>
            <p>Last name: <strong data-bind="text: LastName"></strong></p>

            @*grab values from my second view model that I made*@
            <p>SomeOtherValue <strong data-bind="text: Test2.SomeOtherValue"></strong></p>
            <p>Another <strong data-bind="text: Test2.Another"></strong></p>

            @*allow changes to all the values that should be then sync the above values.*@
            <p>First name: <input data-bind="value: FirstName" /></p>
            <p>Last name: <input data-bind="value: LastName" /></p>
            <p>SomeOtherValue <input data-bind="value: Test2.SomeOtherValue" /></p>
            <p>Another <input data-bind="value: Test2.Another" /></p>

           @* seeing if I can do it with p tags and see if they all update.*@
            <p data-bind="foreach: Test3">
                <strong data-bind="text: Test3Value"></strong> 
            </p>

     @*took my 3rd view model that is in a collection and output all values as a textbox*@       
    <table>
        <thead><tr>
            <th>Test3</th>
        </tr></thead>
          <tbody data-bind="foreach: Test3">
            <tr>
                <td>    
                    <strong data-bind="text: Test3Value"></strong> 
<input type="text" data-bind="value: Test3Value"/>
                </td>
            </tr>    
        </tbody>
    </table>
Run Code Online (Sandbox Code Playgroud)

调节器

  public ActionResult Index()
    {
              Test2 test2 = new Test2
        {
            Another = "test",
            SomeOtherValue = "test2"
        };

        Test vm = new Test
        {
            FirstName = "Bob",
            LastName = "N/A",
             Test2 = test2,

        };
        for (int i = 0; i < 10; i++)
        {
            Test3 test3 = new Test3
            {
                Test3Value = i.ToString()
            };

             vm.Test3.Add(test3);
        }

        return View(vm);
    }
Run Code Online (Sandbox Code Playgroud)

Jup*_*aol 179

我想我已经总结了你的所有问题,如果我错过了什么请告诉我(如果你能在一个地方总结你所有的问题会很好 =))

注意.ko.editable添加了与插件的兼容性

下载完整代码

你如何使用knockout.js的html助手

这很简单:

@Html.TextBoxFor(model => model.CourseId, new { data_bind = "value: CourseId" })
Run Code Online (Sandbox Code Playgroud)

哪里:

  • value: CourseId表示您valueinput控件的CourseId属性与模型和脚本模型中的属性绑定在一起

结果是:

<input data-bind="value: CourseId" data-val="true" data-val-number="The field CourseId must be a number." data-val-required="The CourseId field is required." id="CourseId" name="CourseId" type="text" value="12" />
Run Code Online (Sandbox Code Playgroud)

为什么需要文档才能使其正常工作(有关详细信息,请参阅第一次编辑)

我还不明白为什么你需要使用ready事件来序列化模型,但它似乎只需要它(不过不用担心)

如果我使用我的视图模型的淘汰映射,我该如何做这样的事情?由于映射我没有功能.

如果我理解正确,你需要在KO模型中附加一个新方法,那就是简单的合并模型

有关详细信息,请参阅"从不同来源进行 - 来自 -

function viewModel() {
    this.addStudent = function () {
        alert("de");
    };
};

$(function () {
    var jsonModel = '@Html.Raw(JsonConvert.SerializeObject(this.Model))';
    var mvcModel = ko.mapping.fromJSON(jsonModel);

    var myViewModel = new viewModel();
    var g = ko.mapping.fromJS(myViewModel, mvcModel);

    ko.applyBindings(g);
});
Run Code Online (Sandbox Code Playgroud)

关于你收到的警告

警告1关闭条件编译 - > @ Html.Raw

你需要使用引号

与ko.editable插件的兼容性

我认为它会变得更复杂,但事实证明,集成非常简单,为了使您的模型可编辑,只需添加以下行:(请记住,在这种情况下,我使用的是混合模型,来自服务器和在客户端添加扩展程序,可编辑只是工作...这很棒):

    ko.editable(g);
    ko.applyBindings(g);
Run Code Online (Sandbox Code Playgroud)

从这里你只需要使用插件添加的扩展来玩你的绑定,例如,我有一个按钮开始编辑我的字段,在这个按钮中我开始编辑过程:

    this.editMode = function () {
        this.isInEditMode(!this.isInEditMode());
        this.beginEdit();
    };
Run Code Online (Sandbox Code Playgroud)

然后我使用以下代码提交和取消按钮:

    this.executeCommit = function () {
        this.commit();
        this.isInEditMode(false);
    };
    this.executeRollback = function () {
        if (this.hasChanges()) {
            if (confirm("Are you sure you want to discard the changes?")) {
                this.rollback();
                this.isInEditMode(false);
            }
        }
        else {
            this.rollback();
            this.isInEditMode(false);
        }
    };
Run Code Online (Sandbox Code Playgroud)

最后,我有一个字段来指示字段是否处于编辑模式,这只是绑定enable属性.

this.isInEditMode = ko.observable(false);
Run Code Online (Sandbox Code Playgroud)

关于你的阵列问题

我可能会有一些foreach循环或某些东西来从Student View Models集合中获取数据.

然后,当我提交表单时,我将使用jquery和serialize数组并将其发送到控制器操作方法,该方法将其绑定回viewmodel.

你可以用KO做同样的事情,在下面的例子中,我将创建以下输出:

在此输入图像描述

基本上在这里,你有两个列表,使用Helpers和KO绑定创建,他们有一个dblClick绑定的事件,当被触发时,从当前列表中删除所选项目并将其添加到其他列表,当你发布到Controller每个,每个内容list作为JSON数据发送并重新附加到服务器模型

掘金:

外部脚本.

控制器代码

    [HttpGet]
    public ActionResult Index()
    {
        var m = new CourseVM { CourseId = 12, CourseName = ".Net" };

        m.StudentViewModels.Add(new StudentVm { ID = 545, Name = "Name from server", Lastname = "last name from server" });

        return View(m);
    }

    [HttpPost]
    public ActionResult Index(CourseVM model)
    {
        if (!string.IsNullOrWhiteSpace(model.StudentsSerialized))
        {
            model.StudentViewModels = JsonConvert.DeserializeObject<List<StudentVm>>(model.StudentsSerialized);
            model.StudentsSerialized = string.Empty;
        }

        if (!string.IsNullOrWhiteSpace(model.SelectedStudentsSerialized))
        {
            model.SelectedStudents = JsonConvert.DeserializeObject<List<StudentVm>>(model.SelectedStudentsSerialized);
            model.SelectedStudentsSerialized = string.Empty;
        }

        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

模型

public class CourseVM
{
    public CourseVM()
    {
        this.StudentViewModels = new List<StudentVm>();
        this.SelectedStudents = new List<StudentVm>();
    }

    public int CourseId { get; set; }

    [Required(ErrorMessage = "Course name is required")]
    [StringLength(100, ErrorMessage = "Course name cannot be this long.")]
    public string CourseName { get; set; }

    public List<StudentVm> StudentViewModels { get; set; }
    public List<StudentVm> SelectedStudents { get; set; }

    public string StudentsSerialized { get; set; }
    public string SelectedStudentsSerialized { get; set; }
}

public class StudentVm
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Lastname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

CSHTML页面

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>CourseVM</legend>

        <div>
            <div class="editor-label">
                @Html.LabelFor(model => model.CourseId)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.CourseId, new { data_bind = "enable: isInEditMode, value: CourseId" })
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.CourseName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.CourseName, new { data_bind = "enable: isInEditMode, value: CourseName" })
                @Html.ValidationMessageFor(model => model.CourseName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.StudentViewModels);
            </div>
            <div class="editor-field">

                @Html.ListBoxFor(
                    model => model.StudentViewModels,
                    new SelectList(this.Model.StudentViewModels, "ID", "Name"),
                    new
                    {
                        style = "width: 37%;",
                        data_bind = "enable: isInEditMode, options: StudentViewModels, optionsText: 'Name', value: leftStudentSelected, event: { dblclick: moveFromLeftToRight }"
                    }
                )
                @Html.ListBoxFor(
                    model => model.SelectedStudents,
                    new SelectList(this.Model.SelectedStudents, "ID", "Name"),
                    new
                    {
                        style = "width: 37%;",
                        data_bind = "enable: isInEditMode, options: SelectedStudents, optionsText: 'Name', value: rightStudentSelected, event: { dblclick: moveFromRightToLeft }"
                    }
                )
            </div>

            @Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
            @Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
            @Html.HiddenFor(model => model.StudentsSerialized, new { data_bind = "value: StudentsSerialized" })
            @Html.HiddenFor(model => model.SelectedStudentsSerialized, new { data_bind = "value: SelectedStudentsSerialized" })
        </div>

        <p>
            <input type="submit" value="Save" data-bind="enable: !isInEditMode()" /> 
            <button data-bind="enable: !isInEditMode(), click: editMode">Edit mode</button><br />
            <div>
                <button data-bind="enable: isInEditMode, click: addStudent">Add Student</button>
                <button data-bind="enable: hasChanges, click: executeCommit">Commit</button>
                <button data-bind="enable: isInEditMode, click: executeRollback">Cancel</button>
            </div>
        </p>
    </fieldset>
}
Run Code Online (Sandbox Code Playgroud)

脚本

<script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/ko.editables.js")" type="text/javascript"></script>

<script type="text/javascript">
    var g = null;
    function ViewModel() {
        this.addStudent = function () {
            this.StudentViewModels.push(new Student(25, "my name" + new Date(), "my last name"));
            this.serializeLists();
        };
        this.serializeLists = function () {
            this.StudentsSerialized(ko.toJSON(this.StudentViewModels));
            this.SelectedStudentsSerialized(ko.toJSON(this.SelectedStudents));
        };
        this.leftStudentSelected = ko.observable();
        this.rightStudentSelected = ko.observable();
        this.moveFromLeftToRight = function () {
            this.SelectedStudents.push(this.leftStudentSelected());
            this.StudentViewModels.remove(this.leftStudentSelected());
            this.serializeLists();
        };
        this.moveFromRightToLeft = function () {
            this.StudentViewModels.push(this.rightStudentSelected());
            this.SelectedStudents.remove(this.rightStudentSelected());
            this.serializeLists();
        };
        this.isInEditMode = ko.observable(false);
        this.executeCommit = function () {
            this.commit();
            this.isInEditMode(false);
        };
        this.executeRollback = function () {
            if (this.hasChanges()) {
                if (confirm("Are you sure you want to discard the changes?")) {
                    this.rollback();
                    this.isInEditMode(false);
                }
            }
            else {
                this.rollback();
                this.isInEditMode(false);
            }
        };
        this.editMode = function () {
            this.isInEditMode(!this.isInEditMode());
            this.beginEdit();
        };
    }

    function Student(id, name, lastName) {
        this.ID = id;
        this.Name = name;
        this.LastName = lastName;
    }

    $(function () {
        var jsonModel = '@Html.Raw(JsonConvert.SerializeObject(this.Model))';
        var mvcModel = ko.mapping.fromJSON(jsonModel);

        var myViewModel = new ViewModel();
        g = ko.mapping.fromJS(myViewModel, mvcModel);

        g.StudentsSerialized(ko.toJSON(g.StudentViewModels));
        g.SelectedStudentsSerialized(ko.toJSON(g.SelectedStudents));

        ko.editable(g);
        ko.applyBindings(g);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

注意:我刚刚添加了这些行:

        @Html.HiddenFor(model => model.CourseId, new { data_bind="value: CourseId" })
        @Html.HiddenFor(model => model.CourseName, new { data_bind="value: CourseName" })
Run Code Online (Sandbox Code Playgroud)

因为当我提交表单时,我的字段被禁用,所以值不会传输到服务器,这就是为什么我添加了几个隐藏的字段来做这个技巧


Dar*_*rov 23

您可以将ASP.NET MVC视图模型序列化为javascript变量:

@model CourseVM
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
    // go ahead and use the model javascript variable to bind with ko
</script>
Run Code Online (Sandbox Code Playgroud)

您可以通过淘汰文档中的大量示例进行操作.

  • 是的,我浏览了他们在网站上提供的交互式教程,但我真的从未看到与 asp.net mvc 有任何关系。我看到他们也有一些映射插件,但不确定它如何适合。在您的示例中,您将如何将其绑定到淘汰模型(在另一个脚本中)。我真的想要尽可能少的内联javascript(非更好,但我想这是不可能的) (2认同)
  • 你想解决什么问题?如果您想要MVC视图并对如何使用它们感到满意,那么您可以坚持下去.如果您想要客户端数据绑定和操作,那么KO是一个很好的选择.您可以从MVC代码生成KO视图模型,如此答案所示.它需要vm并将其序列化为json.然后在客户端上,您可以将结果映射到javascript视图模型.然后将viewmodel绑定到视图,您就完成了所有设置.关键是MVC和KO不必以任何方式耦合,除非你想要它们.这一切都取决于你试图解决的问题. (2认同)