在"MVC批量更新,可验证并解决集合元素不连续控制器接收不完全的问题"中,当点击"添加"按钮的时候,通过部分视图,在界面上添加新行。本篇体验使用jQuery Template,在界面上添加新行。

□ 思路

→引用jQuery Template所需要的js文件:jquery.tmpl.min.js
→在<script type="text/x-jquery-tmpl" id="movieTemplate"></script>中生成模版内容,里面包含占位符
→点击添加按钮的时候,把模版内容追加到界面上,并给占位符赋值

 

□ jQuery Template的内容大致是这样:

<script type="text/x-jquery-tmpl" id="movieTemplate">
<li style="padding-bottom:15px">
 
    <input autocomplete="off" name="FavouriteMovies.Index" type="hidden" value="${index}" />
 
    <img src="/Content/images/draggable-icon.png" style="cursor: move" alt=""/>
 
    <label>Title</label>
    <input name="FavouriteMovies[${index}].Title" type="text" value="" />
 
    <label>Rating</label>
    <input name="FavouriteMovies[${index}].Rating" type="text" value="0" />
 
    <a href="#" onclick="$(this).parent().remove();">Delete</a>
</li>
</script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

为了得到以上内容,由帮助类方法获得:

    <script type="text/x-jquery-tmpl" id="movieTemplate">

            @Html.CollectionItemJQueryTemplate("MovieEntryEditor", new Movie())

    </script>

 

帮助类CollectionEditingHtmlExtensions:

模版内容同样是通过MovieEntryEditor.cshtml这个部分视图生成的,只不过生成的内容中包含了占位符。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
 
namespace VariableCollection.Extension
{
    public static class CollectionEditingHtmlExtensions
    {
        /// <summary>
        /// 目标是生成如下格式
        ///<input autocomplete="off" name="FavouriteMovies.Index" type="hidden" value="6d85a95b-1dee-4175-bfae-73fad6a3763b" />
        ///<label>Title</label>
        ///<input class="text-box single-line" name="FavouriteMovies[6d85a95b-1dee-4175-bfae-73fad6a3763b].Title" type="text" value="Movie 1" />
        ///<span class="field-validation-valid"></span>
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="html"></param>
        /// <param name="collectionName">集合属性的名称</param>
        /// <returns></returns>
        public static IDisposable BeginCollectionItem<TModel>(this HtmlHelper<TModel> html, string collectionName)
        {
            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentException("collectionName is null or empty","collectionName");
            }
            string collectionIndexFieldName = String.Format("{0}.Index", collectionName);//FavouriteMovies.Index
            string itemIndex = null;
            if (html.ViewData.ContainsKey(JQueryTemplatingEnabledKey))
            {
                itemIndex = "${index}";
            }
            else
            {
                itemIndex = GetCollectionItemIndex(collectionIndexFieldName);
            }
 
            //比如,FavouriteMovies[6d85a95b-1dee-4175-bfae-73fad6a3763b]
            string collectionItemName = string.Format("{0}[{1}]", collectionName, itemIndex);
 
            TagBuilder indexField = new TagBuilder("input");
            indexField.MergeAttributes(new Dictionary<string, string>() {
                { "name", String.Format("{0}.Index", collectionName) }, //name="FavouriteMovies.Index"
                { "value", itemIndex },//value="6d85a95b-1dee-4175-bfae-73fad6a3763b"
                { "type", "hidden" },
                { "autocomplete", "off" }
            });
            html.ViewContext.Writer.WriteLine(indexField.ToString(TagRenderMode.SelfClosing));
 
            return new CollectionItemNamePrefixScope(html.ViewData.TemplateInfo, collectionItemName);
        }
 
         private class CollectionItemNamePrefixScope : IDisposable
         {
             private readonly TemplateInfo _templateInfo;
             private readonly string _previousPrefix;
 
             public CollectionItemNamePrefixScope(TemplateInfo templateInfo, string collectionItemName)
             {
                 this._templateInfo = templateInfo;
                 _previousPrefix = templateInfo.HtmlFieldPrefix;
                 templateInfo.HtmlFieldPrefix = collectionItemName;
             }
 
             public void Dispose()
             {
                 _templateInfo.HtmlFieldPrefix = _previousPrefix;
             }
         }
 
        /// <summary>
        /// 以FavouriteMovies.Index为键,把Guid字符串存放在上下文中
        /// 如果是添加进入部分视图,就直接生成一个Guid字符串
        /// 如果是更新,为了保持和ModelState的一致,就遍历原先的Guid
        /// </summary>
        /// <param name="collectionIndexFieldName">FavouriteMovies.Index</param>
        /// <returns>返回Guid字符串</returns>
        private static string GetCollectionItemIndex(string collectionIndexFieldName)
        {
            Queue<string> previousIndices = (Queue<string>)HttpContext.Current.Items[collectionIndexFieldName];
            if (previousIndices == null)
            {
                HttpContext.Current.Items[collectionIndexFieldName] = previousIndices = new Queue<string>();
                string previousIndicesValues = HttpContext.Current.Request[collectionIndexFieldName];
                if (!string.IsNullOrWhiteSpace(previousIndicesValues))
                {
                    foreach (string index in previousIndicesValues.Split(','))
                    {
                        previousIndices.Enqueue(index);
                    }
                }
            }
            return previousIndices.Count > 0 ? previousIndices.Dequeue() : Guid.NewGuid().ToString();
        }
 
        private const string JQueryTemplatingEnabledKey = "__BeginCollectionItem_jQuery";
        public static MvcHtmlString CollectionItemJQueryTemplate<TModel, TCollectionItem>(this HtmlHelper<TModel> html,
                                                                                    string partialViewName,
                                                                                    TCollectionItem modelDefaultValues)
        {
            ViewDataDictionary<TCollectionItem> viewData = new ViewDataDictionary<TCollectionItem>(modelDefaultValues);
            viewData.Add(JQueryTemplatingEnabledKey, true);
            return html.Partial(partialViewName, modelDefaultValues, viewData);
        }
    }
}    
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

□ MovieEntryEditor.cshtm部分视图与上篇相同

@using VariableCollection.Extension
@model VariableCollection.Models.Movie
 
<li style="padding-bottom: 15px;">
    @using (Html.BeginCollectionItem("FavouriteMovies"))
    {
        <img src="@Url.Content("~/Content/images/draggable-icon.png")" style="cursor: move" alt=""/>
 
        @Html.LabelFor(model => model.Title)
        @Html.EditorFor(model => model.Title)
        @Html.ValidationMessageFor(model => model.Title)
 
        @Html.LabelFor(model => model.Rating)
        @Html.EditorFor(model => model.Rating)
        @Html.ValidationMessageFor(model => model.Rating)
 
        <a href="#" onclick=" $(this).parent().remove(); ">删除行</a>
    }
</li>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ HomeController

        public ActionResult EditJqueryTemplate()
        {
            return View(CurrentUser);
        }
 
        [HttpPost]
        public ActionResult EditJqueryTemplate(User user)
        {
            if (!this.ModelState.IsValid)
            {
                return View(user);
            }
            CurrentUser = user;
            return RedirectToAction("Display");
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ EditJqueryTemplate.cshtml完整代码如下:

@using VariableCollection.Extension
@using VariableCollection.Models
@model VariableCollection.Models.User
 
@{
    ViewBag.Title = "EditJqueryTemplate";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>EditJqueryTemplate</h2>
 
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>最喜欢看的电影</legend>
        @Html.HiddenFor(model => model.Id)
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
    </fieldset>
    
    <fieldset>
        <legend>最喜欢看的电影</legend>
        @if (Model.FavouriteMovies == null || Model.FavouriteMovies.Count == 0)
        {
            <p>没有喜欢看的电影~~</p>
        }
        <ul id="movieEditor" style="list-style-type: none">
            @if (Model.FavouriteMovies != null)
            {
                foreach (Movie movie in Model.FavouriteMovies)
                {
                    Html.RenderPartial("MovieEntryEditor", movie);
                }
            }
        </ul>
               
        <a id="addAnother" href="#" >添加</a>
    </fieldset>
    <p>
        <input type="submit" value="提交" />
    </p>
}
 
@section scripts
{
    <script src="~/Scripts/jquery.tmpl.min.js"></script>
    
    <script type="text/x-jquery-tmpl" id="movieTemplate">
            @Html.CollectionItemJQueryTemplate("MovieEntryEditor", new Movie())
    </script>
 
    <script type="text/javascript">
            $(function () {
                $("#movieEditor").sortable();
 
                $('#addAnother').click(function() {
                    viewModel.addNew();
                });
            });
 
            var viewModel = {
                addNew: function () {
                    $("#movieEditor").append($("#movieTemplate").tmpl({ index: viewModel._generateGuid() }));
                },
 
                _generateGuid: function () {
                    // Source: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/105074#105074
                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                        return v.toString(16);
                    });
                }
            };
    </script>
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

参考资料:

Editing Variable Length Reorderable Collections in ASP.NET MVC – Part 2: jQuery Templates

MVC批量更新,使用jQuery Template的更多相关文章

  1. MVC批量更新,可验证并解决集合元素不连续控制器接收不完全的问题

    在"MVC批量添加,增加一条记录的同时添加N条集合属性所对应的个体"中,有2个问题待解决: 1.由jquery动态生成了表单元素,但不能实施验证. 2.一旦集合元素不连续,控制器就 ...

  2. Spring批量更新batchUpdate提交和Hibernate批量更新executeUpdate

    1:先看hibernate的批量更新处理. 版本背景:hibernate 5.0.8 applicationContext.xml 配置清单: <?xml version="1.0&q ...

  3. EF结合SqlBulkCopy实现高效的批量数据插入 |EF插件EntityFramework.Extended实现批量更新和删除

    原文链接:http://blog.csdn.net/fanbin168/article/details/51485969   批量插入 (17597条数据批量插入耗时1.7秒)   using Sys ...

  4. mongodb 批量更新 数组的键操作的文件

    persons该文件的数据如下面的: > db.persons.find() { "_id" : 2, "name" : 2 } { "_id& ...

  5. mongodb批量更新操作文档的数组键

    persons文档的数据如下: > db.persons.find(){ "_id" : 2, "name" : 2 }{ "_id" ...

  6. jQuery.template.js 简单使用

    之前看了一篇文章<我们为什么要尝试前后端分离>,深有同感,并有了下面的评论: 我最近也和前端同事在讨论这个问题,比如有时候前端写好页面给后端了,然后后端把这些页面拆分成很多的 views, ...

  7. SQL批量更新 关系表更新

    很多人在做数据的批量更新时..如果更新的内容是从其他表查出来的..很容易这么写.. UPDATE TABLE1 SET COLUMN1=(SELECT SUM(SOMETHING) FROM TABL ...

  8. SQL 将2张不相关的表拼接成2列,批量更新至另一张表

    update SO_Master set LotteryNo=t2.LotteryNo,UpdateTime=GETDATE() --select sm.LotteryNo,sm.SysNo,t2.L ...

  9. [PDO绑定参数]使用PHP的PDO扩展进行批量更新操作

    最近有一个批量更新数据库表中某几个字段的需求,在做这个需求的时候,使用了PDO做参数绑定,其中遇到了一个坑. 方案选择 笔者已知的做批量更新有以下几种方案: 1.逐条更新 这种是最简单的方案,但无疑也 ...

随机推荐

  1. sql server 提取汉字/数字/字母的方法

    sql server 提取汉字/数字/字母的方法 --提取数字 IF OBJECT_ID('DBO.GET_NUMBER2') IS NOT NULL DROP FUNCTION DBO.GET_NU ...

  2. asp.net 微信公众号源码

    需要源码,请加QQ:858-048-581 功能菜单 该源码功能十分的全面,具体介绍如下:1.菜单回复:微信自定义回复.关注时回复.默认回复.文本回复.图文回复.语音回复. 请求回复记录.LBS位置回 ...

  3. OpenCV 颜色空间转换参数CV_BGR2GRAY改变

    OpenCV的颜色空间转换函数:   C++: void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )   参数d ...

  4. sdoi2014-向量集-线段树-二分斜率

    注意到线段树一个节点只有满了才会被用到,那时再建ConvexHull就行了... #include <bits/stdc++.h> using namespace std; namespa ...

  5. easyui tree tabs

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. Zookeeper服务器集群的搭建与操作

    ZooKeeper 作用:Zookeeper 可以用来保证数据在zk集群之间的数据的事务性一致(原子操作). 介绍:Zookeeper 是 Google 的 Chubby一个开源的实现,是 Hadoo ...

  7. 02:实现Singleton模式

    Java实现单例模式有很多种实现方法,其中我们应根据需要选择线程安全的与非线程安全的两种方式,根据对象实现的方式又分为饱汉与饿汉方式. 这里使用java中的volatile关键字与synchroniz ...

  8. TCP、UDP、HTTP、SOCKET之间的区别与联系

    IP:网络层协议: TCP和UDP:传输层协议: HTTP:应用层协议: SOCKET:TCP/IP网络的API. TCP/IP代表传输控制协议/网际协议,指的是一系列协议. TCP和UDP使用IP协 ...

  9. PHP中双引号引起的命令执行漏洞

    前言 在PHP语言中,单引号和双引号都可以表示一个字符串,但是对于双引号来说,可能会对引号内的内容进行二次解释,这就可能会出现安全问题. 正文 举个简单例子 <?php $a = 1; $b = ...

  10. 模板优化 运用 function 及 外部模板

    我们都知道模板是泛型的,但是,它一旦被实例化就会产生一个实例化的副本. 好了,大家应该能够猜到,低效模板和高效模板的差异了 一般的低效模板: 1.泛型实参表达形式多样导致的低效模板 2.多文件引用同一 ...