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…….
}
MVC中利用knockout.js实现动态uniqueId的更多相关文章
- 【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI
原文:[ASP.NET Web API教程]2.3.5 用Knockout.js创建动态UI 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容 ...
- Asp.net Mvc中利用ValidationAttribute实现xss过滤
在网站开发中,需要注意的一个问题就是防范XSS攻击,Asp.net mvc中已经自动为我们提供了这个功能.用户提交数据时时,在生成Action参数的过程中asp.net会对用户提交的数据进行验证,一旦 ...
- 在ASP.NET MVC中使用Knockout实践01,绑定Json对象
本篇体验在ASP.NET MVC下使用Knockout,将使用EF Code First创建数据库.最后让Knockout绑定一个Json对象. 创建一个领域模型. namespace MvcAppl ...
- ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理
话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐 ...
- ASP.NET MVC中使用Dropzone.js实现图片的批量拖拽上传
说在前面 最近在做一个MVC相册的网站(这里),需要批量上传照片功能,所以就在网上搜相关的插件,偶然机会发现Dropzone.js,试用了一下完全符合我的要求,而且样式挺满意的,于是就在我的项目中使用 ...
- MVC中利用自定义的ModelBinder过滤关键字
上一篇主要讲解了如何利用ActionFilter过滤关键字,这篇主要讲解如何利用自己打造的ModelBinder来过滤关键字. 首先,我们还是利用上一篇中的实体类,但是我们需要加上DataType特性 ...
- MVC中利用ActionFilterAttribute过滤关键字
在开发过程中,有时候会对用户输入进行过滤,以便保证平台的安全性.屏蔽的方法有很多种,但是今天我说的这种主要是利用MVC中的ActionFilterAttribute属性来实现.由于MVC天然支持AOP ...
- MVC中的时间js格式化
记录下我遇到的一个,MVC中post请求返回一个JSON字符串,其中包含数据库中的时间格式(如:/Date(10000000000)/),不知道怎么处理.百度的方法都不适用,经自己研究,做成了一个Jq ...
- ASP.NET MVC 中单独的JS文件中获取Controller中设定的值
1,在Controller中的Action 中将指定值写上. // // GET: /Home/ public ActionResult Index() ...
随机推荐
- AMQP协议与RabbitMQ、MQ消息队列的应用场景
什么是AMQP? 在异步通讯中,消息不会立刻到达接收方,而是被存放到一个容器中,当满足一定的条件之后,消息会被容器发送给接收方,这个容器即消息队列,而完成这个功能需要双方和容器以及其中的各个组件遵守统 ...
- 定时删除文件夹"$1"下最后修改时间大于当前时间"$2"天的文件
shell 脚本: #!/bin/bash now=`date "+%Y-%m-%d_%H:%M:%S"` #获取当前时间 echo "当前时间: " ...
- linux 安装nexus3
准备工作: 环境:linux 系统:centos6.4-x86-x64 安装工具:nexus-3.14 软件下载:nexus-3.14 官网下载地址:点击打开链接 将下载的压缩包通过xft5上传至/o ...
- pip 离线安装
pip download ansible -d . --trusted-host mirrors.aliyun.com pip install ansible-2.7.5.tar.gz --user ...
- appium自动化测试之UIautomatorviewer元素定位
appium自动化测试之UIautomatorviewer元素定位 标签(空格分隔): uiautomatorviewer元素定位 前面的章节,已经总结了怎么搭建环境,怎样成功启动一个APP了,这里具 ...
- python学习day9 字符编码和文件处理
1.字符编码 x='上' #unicode的二进制--------->编码-------->gbk格式的二进制 res=x.encode('gbk') #bytes 字节类型 print( ...
- AttributeError: 'dict' object has no attribute 'iteritems'
在python3.6中运行 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse= ...
- PAT1018 (dijkstra+dfs)
There is a public bike service in Hangzhou City which provides great convenience to the tourists fro ...
- 用webstorm开发前端项目前的一些配置
每日的开发都在紧张中进行,代码的运用和流通性大,有些想酝酿品尝的东西,来不及停留而留下遗憾,基于此,想起几次前辈们的建议,用写博客来记录这些曾在我们内心荡漾的一些东西. 需要安装的软件:WebStor ...
- webpack.dev.conf.js
var utils = require('./utils')var webpack = require('webpack')var config = require('../config') // 一 ...