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() ...
随机推荐
- react ES5 与ES6的写法
ES5var React = require('react'); var ReactDOM = require('react-dom'); // 定义组件 var HelloMessage = Rea ...
- 2018面向对象程序设计(Java) 第2周学习指导及要求
2018面向对象程序设计(Java) 第2周学习指导及要求(2018.9.3-2018.9.9) 学习目标 适应老师教学方式,能按照自主学习要求完成本周理论知识学习: 掌握Java Applica ...
- 2.6、CDH 搭建Hadoop在安装(安装CDH和其他软件)
第6步:安装CDH和其他软件 设置Cloudera Manager数据库后,启动Cloudera Manager Server,然后登录Cloudera Manager Admin Console: ...
- Animator状态快速切换问题
[Animator状态快速切换问题] 事情是这样的,我尝试在一帧内多次切换一些状态(当前状态为Idle的情况下): public Animator animator; void OnEnable() ...
- msf客户端渗透(一):payload利用简单示范
针对Windows 开启侦听 查看payload选项 将1.exe传到网页上 win7访问网页并下载1.exe 下载好之后双击运行,在服务器端就获得了一个shell 针对linux 先获取到一个软 ...
- 区分action, service和dao
在这里,我们不仅要处理页面逻辑,还要做业务逻辑,还要做数据访问.比如说: public String addUser() { if(user == null) { return FAIL_NO_USE ...
- Linux 字符设备驱动及一些简单的Linux知识
一.linux系统将设备分为3类:字符设备.块设备.网络设备 1.字符设备:是指只能一个字节一个字节读写的设备,不能随机读取设备内存中的某一数据,读取数据需要按照先后数据.字符设备是面向流的设备,常见 ...
- 22. Generate Parentheses (backTracking)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- #define宏重定义
#define A 1 在同一个工程的另外一个文件里又定义了#define A 2 并不会报错(2010vs) 亲测可用 但是最后该宏变量A的值 ,应该是预处理-----顺序处理------最后一个运 ...
- Spring <context:annotation-config> 和 <context:component-scan> 区别
一篇很不错的文章,看到就是赚到Get.... https://www.cnblogs.com/leiOOlei/p/3713989.html 说白了 :<context:component-sc ...