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() ...
随机推荐
- css 书目录相关css+html代码
css: <style type="text/css"> #list{width:500px;position:absolute;left:50%;margin-lef ...
- sql语句查询菜单结果成 树状图类型 注意适用于id是四位数
select * from ( select pid,id,name,url,concat(id,":") idOrder from menu where pid=0 and st ...
- SQL Server子查询填充DataSet时报500内部错误的解决办法
运行环境为Visual Studio 2010,数据库为SQL Server 2008. 执行下面SQL语句 SELECT SubsiteId, SubsiteTitle, count(Collect ...
- C# delegate (001)
背景:一直不是很理解C#中的委托,也不是很清楚委托应用的业务场景,有可能和自己一直做B/S有关 业务描述:C/S,父窗口打开子窗口,子窗口把自己文本框里的值传个父窗口的文本框. 子窗体代码: //定义 ...
- leetcode 数组类型题
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h& ...
- 第十章 优先级队列 (xa1)左式堆:结构
- CentOS 7 单用户模式+救援模式
CentOS 7 单用户模式+救援模式 CentOS 7 单用户模式+救援模式.有时候大家可能会忘记自己的root密码,或者错误(命令输入错误,命令位置输入有误等)编辑了一个/etc目录下的核心文件导 ...
- LibreOJ 6282. 数列分块入门 6
题目链接:https://loj.ac/problem/6282 参考博客:http://www.cnblogs.com/stxy-ferryman/p/8560551.html 这里如果用数组的话元 ...
- 1. Two Sum (快速排序;有序数组的查找: 两个指针; 哈希表)
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- 转Genymetion
http://www.cnblogs.com/rainboy2010/p/6387770.html 介绍 Genymotion是一款出色的跨平台的Android模拟器,具有容易安装和使用.运行速度快的 ...