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() ...
随机推荐
- Ubuntu中更改所有子文件和子目录所有者权限
转自:http://www.linuxidc.com/Linux/2015-03/114695.htm Ubuntu中有两个修改命令可以用到,「change mode」&「change own ...
- SSH 登录时出现如下错误:Disconnected:No supported authentication methods available
SSH 登录时出现如下错误:Disconnected:No supported authentication methods available 更新时间:2017-06-07 13:26:11 ...
- putty 链接亚马逊服务器
使用 PuTTY 从 Windows 连接到亚马逊云的 Linux 实例 转载 2016年07月22日 14:09:47 使用 PuTTY 从 Windows 连接到亚马逊云的 Linux 实例 ...
- gradle 很好用的么
Gradle 其实是很好用的 2017, Apr 14 by Tesla Ice Zhang Gradle 是一款使用 Kotlin (划掉) Groovy 编写的 JVM 构建工具,其易用性和 Ma ...
- opencv 对RGB图像直接二值化
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace st ...
- Spark Streaming之五:Window窗体相关操作
SparkStreaming之window滑动窗口应用,Spark Streaming提供了滑动窗口操作的支持,从而让我们可以对一个滑动窗口内的数据执行计算操作.每次掉落在窗口内的RDD的数据,会被聚 ...
- kali安装显卡驱动
由于我们使用cpu一般最多也就是4到16核,而一块不错的gpu可以多大上千核,在并行复杂运算能力上GPU的运算速度远远超过CPU的运算速度,所以很多场合比如暴力穷举破解,挖矿更多地使用GPU,所以有必 ...
- spark快速开发之scala基础之1 数据类型与容器
写在前面 面向java开发者.实际上,具有java基础学习scala是很容易.java也可以开发spark,并不比scala开发的spark程序慢.但学习scala可有助于更快更好的理解spark.比 ...
- Python Flask Jinja2模板引擎
模板 简介 模板是一个包含响应文本的文件,其中包含用占位变量表示的动态部分,其具体值只在请 求的上下文中才能知道. 渲染 使用真实值替换变量,再返回最终得到的响应字符串,这一过程 称为渲染.为了渲染模 ...
- 以字符串形式获取excel单元格中的内容
public static String getCellValue(XSSFCell cell) { if (cell == null) { return ""; } switch ...