MVC批量更新,使用jQuery Template
2020-12-13 02:22
标签:style blog class code java tar 在"MVC批量更新,可验证并解决集合元素不连续控制器接收不完全的问题"中,当点击"添加"按钮的时候,通过部分视图,在界面上添加新行。本篇体验使用jQuery
Template,在界面上添加新行。 □ 思路 →引用jQuery Template所需要的js文件:jquery.tmpl.min.js □ jQuery Template的内容大致是这样:
为了得到以上内容,由帮助类方法获得: 帮助类CollectionEditingHtmlExtensions: □ HomeController □
EditJqueryTemplate.cshtml完整代码如下: MVC批量更新,使用jQuery Template,搜素材,soscw.com MVC批量更新,使用jQuery Template 标签:style blog class code java tar 原文地址:http://www.cnblogs.com/darrenji/p/3717770.html
→在中生成模版内容,里面包含占位符
→点击添加按钮的时候,把模版内容追加到界面上,并给占位符赋值
"off" name="FavouriteMovies.Index" type="hidden" value="${index}" />
"/Content/images/draggable-icon.png" style="cursor: move" alt=""/>
"FavouriteMovies[${index}].Title" type="text" value="" />
"FavouriteMovies[${index}].Rating" type="text" value="0" />
"#" onclick="$(this).parent().remove();">Delete
模版内容同样是通过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
{
///
/// 目标是生成如下格式
///
///
///
///
///
///
///
/// 集合属性的名称
///
public static IDisposable BeginCollectionItem
{
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 Dictionarystring, 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;
}
}
///
/// 以FavouriteMovies.Index为键,把Guid字符串存放在上下文中
/// 如果是添加进入部分视图,就直接生成一个Guid字符串
/// 如果是更新,为了保持和ModelState的一致,就遍历原先的Guid
///
/// FavouriteMovies.Index
///
private static string GetCollectionItemIndex(string collectionIndexFieldName)
{
Queuestring> previousIndices = (Queuestring>)HttpContext.Current.Items[collectionIndexFieldName];
if (previousIndices == null)
{
HttpContext.Current.Items[collectionIndexFieldName] = previousIndices = new Queuestring>();
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
string partialViewName,
TCollectionItem modelDefaultValues)
{
ViewDataDictionary
viewData.Add(JQueryTemplatingEnabledKey, true);
return html.Partial(partialViewName, modelDefaultValues, viewData);
}
}
}
□
MovieEntryEditor.cshtm部分视图与上篇相同@using VariableCollection.Extension
@model VariableCollection.Models.Movie
@using (Html.BeginCollectionItem("FavouriteMovies"))
{
"@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)
"#" onclick=" $(this).parent().remove(); ">删除行
}
public ActionResult EditJqueryTemplate()
{
return View(CurrentUser);
}
[HttpPost]
public ActionResult EditJqueryTemplate(User user)
{
if (!this.ModelState.IsValid)
{
return View(user);
}
CurrentUser = user;
return RedirectToAction("Display");
}
@using VariableCollection.Extension
@using VariableCollection.Models
@model VariableCollection.Models.User
@{
ViewBag.Title = "EditJqueryTemplate";
Layout = "~/Views/Shared/_Layout.cshtml";
}
EditJqueryTemplate
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
"submit" value="提交" />
}
@section scripts
{
@Html.CollectionItemJQueryTemplate("MovieEntryEditor", new Movie())
$(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);
});
}
};
}
参考资料:
※ Editing Variable Length Reorderable Collections in ASP.NET MVC –
Part 2: jQuery Templates