为ASP.Net MVC生成敲除绑定的代码

时间:2014-05-21 08:32:00

标签: asp.net-mvc knockout.js

我曾经淘汰了一下。它是一个很好的客户端数据绑定js库。模板在客户端绑定并填充如下:

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>Delete</legend>
    <div class="display-label">
        Student Id
    </div>
    <div class="display-field">
        <input data-bind="value: StudentId" />

    </div>
    <div class="display-label">
        First Name
    </div>
    <div class="display-field">
        <input data-bind="value: FirstName" />
    </div>

    <div class="display-label">
        Last Name
    </div>
    <div class="display-field">
        <input data-bind="value: LastName" />

    </div>

    <div class="display-label">
        Age
    </div>
    <div class="display-field">
        <input data-bind="value: Age" />

    </div>
</fieldset>

the above way we write html to bind data

this way populate template by js code

$(function () {
    ko.applyBindings(StudentListVM);
    StudentListVM.getStudents();
});

//View Model
var StudentListVM = {
    Students: ko.observableArray([]),
    getStudents: function () {
        var self = this;
        $.ajax({
            type: "GET",
            url: '/Student/FetchStudents',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                self.Students(data); //Put the response in ObservableArray
            },
            error: function (err) {
                alert(err.status + " : " + err.statusText);
            }
        });
    },
};

self.editStudent = function (student) {
    window.location.href =  '/Student/Edit/' + student.StudentId;
};
self.deleteStudent = function (student) {
    window.location.href = '/Student/Delete/' + student.StudentId;
};

//Model
function Students(data) {
    this.StudentId = ko.observable(data.StudentId);
    this.FirstName = ko.observable(data.FirstName);
    this.LastName = ko.observable(data.LastName);
}

以上代码可以在客户端生成并生成UI。

我想知道MVC中是否有任何脚手架选项可以生成带有绑定表达式的上述html,还可以生成所需的js视图模型。

如果不存在,那么我会很感激如何实现它的建议。

1 个答案:

答案 0 :(得分:0)

  • 查看Knockout mvc
  • 您可以编写适当的@helper方法
  • 不要忘记T4
  • 您可以为HtmlHelper
  • 编写自己的扩展程序