MVC中利用knockout.js实现动态uniqueId
题目比较拗口,但是这篇文章确实直说这一点。
knockout.js是一个JS库,它的官网是http://knockoutjs.com/
这篇文章的重点是knockout在工作的一个功能中的应用。最终效果图如下:
点击Add Other Source UI添加一个空行
现有行可以直接修改
点击delete UI删除当前行
点击保存时数据才会录入到服务器
Html代码如下
<div class="row">
<span class="label">Information from other sources:</span>
<table class="inline-dataTable">
<thead>
<tr>
<td>
Test
</td>
<td>
Date
</td>
<td>
Scores
</td>
<td>
Action
</td>
</tr>
</thead>
<tbody data-bind="foreach: OtherSources">
<tr>
<td>
<input required="required" class="required" data-bind="value: Test, uniqueName: true, uniqueId: Test" /><span
class="field-validation-valid" data-bind="valmsg: true" data-valmsg-replace="true" />
</td>
<td>
<input id="Date" class="Date required noFutureDate" required="required" data-bind="value: Date, uniqueName: true, dateName: true, uniqueId: Date" /><span
class="field-validation-valid" data-bind="valmsg: true" data-valmsg-replace="true" />
</td>
<td>
<input required="required" class="required number" data-bind="value: Scores, uniqueName: true, uniqueId: Scores" /><span
class="field-validation-valid" data-bind="valmsg: true" data-valmsg-replace="true" />
</td>
<td>
<a href="#" data-bind="click: function(){ viewModel.removeOtherSource($data) } ">delete</a>
</td>
</tr>
</tbody>
</table>
<div class="add-button">
<a href="#" id="ButtonAddOtherSource" data-bind="click: addOtherSource">Add Other Source</a>
</div>
</div>
Js代码如下:
$(document).ready(function () { // NOTE: KnockoutJS unique id generator (http://stackoverflow.com/questions/9233176/unique-ids-in-knockout-js-templates) ko.bindingHandlers.uniqueId = { init: function (element, valueAccessor) { var value = valueAccessor(); value.id = value.id || ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter); element.id = value.id; }, counter: 0, prefix: "unique" }; // 这是为每个element生成不同ID ko.bindingHandlers['uniqueName'] = { 'currentIndex': 0, 'init': function (element, valueAccessor) { if (valueAccessor()) { element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex); // Workaround IE 6/7 issue // - https://github.com/SteveSanderson/knockout/issues/197 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/ if (ko.utils.isIe6 || ko.utils.isIe7) element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false); } } }; // 这是为每个element生成不同Name ko.bindingHandlers['dateName'] = { init: function (element, valueAccessor) { if (valueAccessor()) { $('#' + element.id).kendoDatePicker({ format: "MM/dd/yyyy" }); } } }; //这是为包含dateName的元素添加了一个DatePicker
ko.bindingHandlers.valmsg = { init: function (element) { element.setAttribute("data-valmsg-for", "ko_unique_" + ko.bindingHandlers.uniqueName.currentIndex); } }; //这是利用element的name显示验证信息
ko.applyBindings(viewModel); }); var OtherSource = function(data) { var self = this; self.Test = ko.observable(data.Test); self.Date = ko.observable(data.Date); self.Scores = ko.observable(data.Scores); }; @{ var otherSources = Json.Encode(Model..........); } var jsonOtherSources = @Html.Raw(otherSources); var viewModel = { OtherSources: ko.observableArray(ko.utils.arrayMap(jsonOtherSources, function(otherSource) { return new OtherSource(otherSource); })), addOtherSource: function() { this.OtherSources.push({ Test: ko.observable(""), Date: ko.observable(""), Scores: ko.observable("") }); }, removeOtherSource: function(otherSource) { this.OtherSources.remove(otherSource); }, };
上述代码的data-bind,addOtherSource,removeOtherSource等在官网都有详细的说明。
那我就只说一下在项目中出现的代码。
uniqueId ,uniqueName是增加的一些属性,用来做验证。最终生成的Html如下:
这样就生成了MVC中 ValidationMessageFor类似的验证代码,帮助我们在在页面层进行验证
当看到uniqueId ,uniqueName的绑定和生成方式之后,觉得这代码N。
这也是我要这篇文章的最初原因。
最后再来一点与本题无关,但是保存时候的需要用到的代码吧
if ($("form#editForm").valid()) {
var data = $.deparam($("form#editForm").serialize());
data["OtherSources"] = ko.mapping.toJSON(viewModel.OtherSources);
$.post('@Url.Action("actionName", "ctlName", new {area = "***"})', data, function(result) {
HandleAjaxResult(result);
});
}
var otherSources = Request.Form["OtherSources"];
if (!string.IsNullOrEmpty(otherSources))
{
var otherSourceDtos = JsonConvert.DeserializeObject<List<OtherSourceDto>>(otherSources);
//save data to db…….
}