本篇实践在ASP.NET MVC 4下使用Session来保持表单的状态。

本篇的源码在这里: https://github.com/darrenji/KeepFormStateUsingSession

如上,输入俱乐部名称,点击"添加球员",输入球员名称。我们希望,点击"到别的地方转转"跳转到另外一个视图页,当再次返回的时候能保持表单的状态。

点击"到别的地方转转"跳转到另外一个视图页如下:

再次返回,表单的状态被保持了:

点击"提交"按钮,显示表单的内容:

关于球员,对应的Model为:

  1. using System.ComponentModel.DataAnnotations;
  2.  
  3. namespace MvcApplication1.Models
  4.  
  5. {
  6.  
  7.     public class Player
  8.  
  9.     {
  10.  
  11.         public int Id { get; set; }
  12.  
  13.         [Required(ErrorMessage = "必填")]
  14.  
  15.         [Display(Name = "球员名称")]
  16.  
  17.         public string Name { get; set; }
  18.  
  19.     }
  20.  
  21. }
  22.  

关于俱乐部,对应的Model为:

  1. using System.Collections.Generic;
  2.  
  3. using System.ComponentModel.DataAnnotations;
  4.  
  5. namespace MvcApplication1.Models
  6.  
  7. {
  8.  
  9.     public class Club
  10.  
  11.     {
  12.  
  13.         public Club()
  14.  
  15.         {
  16.  
  17.             this.Players = new List<Player>();
  18.  
  19.         }
  20.  
  21.         public int Id { get; set; }
  22.  
  23.         [Required(ErrorMessage = "必填")]
  24.  
  25.         [Display(Name = "俱乐部名称")]
  26.  
  27.         public string Name { get; set; }
  28.  
  29.         public List<Player> Players { get; set; }
  30.  
  31.     }
  32.  
  33. }
  34.  

在Home/Index.cshtml强类型视图中,

  1. @model MvcApplication1.Models.Club
  2.  
  3. @{
  4.  
  5.     ViewBag.Title = "Index";
  6.  
  7.     Layout = "~/Views/Shared/_Layout.cshtml";
  8.  
  9. }
  10.  
  11. <h2>Index</h2>
  12.  
  13. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new {id = "myForm"}))
  14.  
  15. {
  16.  
  17.     @Html.LabelFor(m => m.Name)
  18.  
  19.     @Html.TextBoxFor(m => m.Name)
  20.  
  21.     @Html.ValidationMessageFor(m => m.Name)
  22.  
  23.     <br/><br/>
  24.  
  25.     <ul id="players" style="list-style-type: none">
  26.  
  27.         @if (Model.Players != null)
  28.  
  29.         {
  30.  
  31.             foreach (var item in Model.Players)
  32.  
  33.             {
  34.  
  35.                 Html.RenderAction("NewPlayerRow", "Home", new { player = @item });
  36.  
  37.             }
  38.  
  39.         }
  40.  
  41.     </ul>
  42.  
  43.     <a id="addPlayer" href="javascript:void(0)">添加球员</a>
  44.  
  45.     <br/><br/>
  46.  
  47.     <div>
  48.  
  49.         <a href="javascript:void(0)"  id="gotoOther">到别的地方转转</a> &nbsp;
  50.  
  51.         <input type="submit" id="up" value="提交" />
  52.  
  53.     </div>
  54.  
  55. }
  56.  
  57. @section scripts
  58.  
  59. {
  60.  
  61.     <script src="~/Scripts/dynamicvalidation.js"></script>
  62.  
  63.     <script type="text/javascript">
  64.  
  65.         $(function () {
  66.  
  67.             //添加关于Player的新行
  68.  
  69.             $('#addPlayer').on("click", function() {
  70.  
  71.                 createPlayerRow();
  72.  
  73.             });
  74.  
  75.             //到别的页
  76.  
  77.             $('#gotoOther').on("click", function() {
  78.  
  79.                 if ($('#myForm').valid()) {
  80.  
  81.                     $.ajax({
  82.  
  83.                         cache: false,
  84.  
  85.                         url: '@Url.Action("BeforeGoToMustSave", "Home")',
  86.  
  87.                         type: 'POST',
  88.  
  89.                         dataType: 'json',
  90.  
  91.                         data: $('#myForm').serialize(),
  92.  
  93.                         success: function (data) {
  94.  
  95.                             if (data.msg) {
  96.  
  97.                                 window.location.href = '@Url.Action("RealGoTo", "Home")';
  98.  
  99.                             }
  100.  
  101.                         },
  102.  
  103.                         error: function (xhr, status) {
  104.  
  105.                             alert("添加失败,状态码:" + status);
  106.  
  107.                         }
  108.  
  109.                     });
  110.  
  111.                 }
  112.  
  113.             });
  114.  
  115.         });
  116.  
  117.         //添加品牌行
  118.  
  119.         function createPlayerRow() {
  120.  
  121.             $.ajax({
  122.  
  123.                 cache: false,
  124.  
  125.                 url: '@Url.Action("NewPlayerRow", "Home")',
  126.  
  127.                 type: "GET",
  128.  
  129.                 data: {},
  130.  
  131.                 success: function (data) {
  132.  
  133.                     $('#players').append(data);
  134.  
  135.                     $.validator.unobtrusive.parseDynamicContent('#players li:last', "#myForm");
  136.  
  137.                 },
  138.  
  139.                 error: function (xhr, status) {
  140.  
  141.                     alert("添加行失败,状态码:" + status);
  142.  
  143.                 }
  144.  
  145.             });
  146.  
  147.         }
  148.  
  149.     </script>
  150.  
  151. }
  152.  

以上,
○ 点击"添加球员",向控制器发出异步请求,把部分视图li动态加载到ul中
○ 点击"到别的地方转转",向控制器发出异步请求,正是在这时候,在控制器的Action中,实施把表单的状态保存到Session中
○ 点击"提交"按钮,把表单信息显示出来

另外,当在页面上点击"添加球员",为了让动态的部分视图能被验证,需要引入dynamicvalidation.js,调用其$.validator.unobtrusive.parseDynamicContent('#players li:last', "#myForm")方法,dynamicvalidation.js具体如下:

  1. //对动态生成内容客户端验证
  2.  
  3. (function ($) {
  4.  
  5.     $.validator.unobtrusive.parseDynamicContent = function (selector, formSelector) {
  6.  
  7.         $.validator.unobtrusive.parse(selector);
  8.  
  9.         var form = $(formSelector);
  10.  
  11.         var unobtrusiveValidation = form.data('unobtrusiveValidation');
  12.  
  13.         var validator = form.validate();
  14.  
  15.         $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
  16.  
  17.             if (validator.settings.rules[elname] == undefined) {
  18.  
  19.                 var args = {};
  20.  
  21.                 $.extend(args, elrules);
  22.  
  23.                 args.messages = unobtrusiveValidation.options.messages[elname];
  24.  
  25.                 //edit:use quoted strings for the name selector
  26.  
  27.                 $("[name='" + elname + "']").rules("add", args);
  28.  
  29.             } else {
  30.  
  31.                 $.each(elrules, function (rulename, data) {
  32.  
  33.                     if (validator.settings.rules[elname][rulename] == undefined) {
  34.  
  35.                         var args = {};
  36.  
  37.                         args[rulename] = data;
  38.  
  39.                         args.messages = unobtrusiveValidation.options.messages[elname][rulename];
  40.  
  41.                         //edit:use quoted strings for the name selector
  42.  
  43.                         $("[name='" + elname + "']").rules("add", args);
  44.  
  45.                     }
  46.  
  47.                 });
  48.  
  49.             }
  50.  
  51.         });
  52.  
  53.     };
  54.  
  55. })(jQuery);

具体原理,请参考"Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC"这篇文章。

在HomeController中,

  1.    public class HomeController : Controller
  2.  
  3.     {
  4.  
  5.         private const string sessionKey = "myFormKey";
  6.  
  7.         public ActionResult Index()
  8.  
  9.         {
  10.  
  11.             Club club = null;
  12.  
  13.             if (Session[sessionKey] != null)
  14.  
  15.             {
  16.  
  17.                 club = (Club) Session[sessionKey];
  18.  
  19.             }
  20.  
  21.             else
  22.  
  23.             {
  24.  
  25.                 club = new Club();
  26.  
  27.             }
  28.  
  29.             return View(club);
  30.  
  31.         }
  32.  
  33.         //提交表单
  34.  
  35.         [HttpPost]
  36.  
  37.         public ActionResult Index(Club club)
  38.  
  39.         {
  40.  
  41.             if (ModelState.IsValid)
  42.  
  43.             {
  44.  
  45.                 StringBuilder sb = new StringBuilder();
  46.  
  47.                 sb.Append(club.Name);
  48.  
  49.                 if (club.Players != null && club.Players.Count > 0)
  50.  
  51.                 {
  52.  
  53.                     foreach (var item in club.Players)
  54.  
  55.                     {
  56.  
  57.                         sb.AppendFormat("--{0}", item.Name);
  58.  
  59.                     }
  60.  
  61.                 }
  62.  
  63.                 //删除Session
  64.  
  65.                 //Session.Abandon();
  66.  
  67.                 //Session.Clear();
  68.  
  69.                 Session.Remove(sessionKey);
  70.  
  71.                 return Content(sb.ToString());
  72.  
  73.             }
  74.  
  75.             else
  76.  
  77.             {
  78.  
  79.                 return View(club);
  80.  
  81.             }
  82.  
  83.         }
  84.  
  85.         //添加新行
  86.  
  87.         public ActionResult NewPlayerRow(Player player)
  88.  
  89.         {
  90.  
  91.             return PartialView("_NewPlayer", player ?? new Player());
  92.  
  93.         }
  94.  
  95.         //跳转之前把表单保存到Session中
  96.  
  97.         [HttpPost]
  98.  
  99.         public ActionResult BeforeGoToMustSave(Club club)
  100.  
  101.         {
  102.  
  103.             Session[sessionKey] = club;
  104.  
  105.             return Json(new { msg = true });
  106.  
  107.         }
  108.  
  109.         //保存完Club的Session后真正跳转到的页面
  110.  
  111.         public ActionResult RealGoTo()
  112.  
  113.         {
  114.  
  115.             return View();
  116.  
  117.         }
  118.  
  119.     }
  120.  

以上,
○ 对于接收[HttpGet]请求的Index方法对应的视图,Session存在就从Session中取出Club实例,否则就创建一个空的club实例
○ 对于接收[HttpPost]请求的Index方法对应的视图,显示表单内容之前把对应的Session删除
○ 添加新行NewPlayerRow方法供显示或添加用,当Player类型参数为null的时候,实际就是点击"添加球员"显示新行
○ BeforeGoToMustSave方法实际是为了在跳转之前保存Session
○ RealGoTo是点击"到别的地方转转"后真正跳转的视图页

另外,所有视图页的公共页Layout.cshtml,必须引用异步验证的js。

  1. <head>
  2.  
  3.     <meta charset="utf-8" />
  4.  
  5.     <meta name="viewport" content="width=device-width" />
  6.  
  7.     <title>@ViewBag.Title</title>
  8.  
  9.     @Styles.Render("~/Content/css")
  10.  
  11.     @Scripts.Render("~/bundles/jquery")
  12.  
  13.     @Scripts.Render("~/bundles/jqueryval")
  14.  
  15. </head>
  16.  
  17. <body>
  18.  
  19.     @RenderBody()
  20.  
  21.     @RenderSection("scripts", required: false)
  22.  
  23. </body>
  24.  

Home/_NewPlayer.cshtml部分视图,是在点击"添加球员"之后动态加载的部分视图。

  1. @using MvcApplication1.Extension
  2.  
  3. @model MvcApplication1.Models.Player
  4.  
  5. <li  class="newcarcolorli">
  6.  
  7.      @using (Html.BeginCollectionItem("Players"))
  8.  
  9.      {
  10.  
  11.         @Html.HiddenFor(model => model.Id)
  12.  
  13.          <div>
  14.  
  15.              @Html.LabelFor(m => m.Name)
  16.  
  17.              @Html.TextBoxFor(m => m.Name)
  18.  
  19.              @Html.ValidationMessageFor(m => m.Name)
  20.  
  21.          </div>
  22.  
  23.      }
  24.  
  25. </li>
  26.  

其中,用到了扩展Extension文件夹下CollectionEditingHtmlExtensions类的扩展方法,如下:

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Web;
  6.  
  7. using System.Web.Mvc;
  8.  
  9. namespace MvcApplication1.Extension
  10.  
  11. {
  12.  
  13.     public static class CollectionEditingHtmlExtensions
  14.  
  15.     {
  16.  
  17.         //目标生成如下格式
  18.  
  19.         //<input autocomplete="off" name="FavouriteMovies.Index" type="hidden" value="6d85a95b-1dee-4175-bfae-73fad6a3763b" />
  20.  
  21.         //<label>Title</label>
  22.  
  23.         //<input class="text-box single-line" name="FavouriteMovies[6d85a95b-1dee-4175-bfae-73fad6a3763b].Title" type="text" value="Movie 1" />
  24.  
  25.         //<span class="field-validation-valid"></span>
  26.  
  27.         public static IDisposable BeginCollectionItem<TModel>(this HtmlHelper<TModel> html, string collectionName)
  28.  
  29.         {
  30.  
  31.             //构建name="FavouriteMovies.Index"
  32.  
  33.             string collectionIndexFieldName = string.Format("{0}.Index", collectionName);
  34.  
  35.             //构建Guid字符串
  36.  
  37.             string itemIndex = GetCollectionItemIndex(collectionIndexFieldName);
  38.  
  39.             //构建带上集合属性+Guid字符串的前缀
  40.  
  41.             string collectionItemName = string.Format("{0}[{1}]", collectionName, itemIndex);
  42.  
  43.             TagBuilder indexField = new TagBuilder("input");
  44.  
  45.             indexField.MergeAttributes(new Dictionary<string, string>()
  46.  
  47.             {
  48.  
  49.                 {"name", string.Format("{0}.Index", collectionName)},
  50.  
  51.                 {"value", itemIndex},
  52.  
  53.                 {"type", "hidden"},
  54.  
  55.                 {"autocomplete", "off"}
  56.  
  57.             });
  58.  
  59.             html.ViewContext.Writer.WriteLine(indexField.ToString(TagRenderMode.SelfClosing));
  60.  
  61.             return new CollectionItemNamePrefixScope(html.ViewData.TemplateInfo, collectionItemName);
  62.  
  63.         }
  64.  
  65.         private class CollectionItemNamePrefixScope : IDisposable
  66.  
  67.         {
  68.  
  69.             private readonly TemplateInfo _templateInfo;
  70.  
  71.             private readonly string _previousPrfix;
  72.  
  73.             //通过构造函数,先把TemplateInfo以及TemplateInfo.HtmlFieldPrefix赋值给私有字段变量,并把集合属性名称赋值给TemplateInfo.HtmlFieldPrefix
  74.  
  75.             public CollectionItemNamePrefixScope(TemplateInfo templateInfo, string collectionItemName)
  76.  
  77.             {
  78.  
  79.                 this._templateInfo = templateInfo;
  80.  
  81.                 this._previousPrfix = templateInfo.HtmlFieldPrefix;
  82.  
  83.                 templateInfo.HtmlFieldPrefix = collectionItemName;
  84.  
  85.             }
  86.  
  87.             public void Dispose()
  88.  
  89.             {
  90.  
  91.                 _templateInfo.HtmlFieldPrefix = _previousPrfix;
  92.  
  93.             }
  94.  
  95.         }
  96.  
  97.         /// <summary>
  98.  
  99.         ///
  100.  
  101.         /// </summary>
  102.  
  103.         /// <param name="collectionIndexFieldName">比如,FavouriteMovies.Index</param>
  104.  
  105.         /// <returns>Guid字符串</returns>
  106.  
  107.         private static string GetCollectionItemIndex(string collectionIndexFieldName)
  108.  
  109.         {
  110.  
  111.             Queue<string> previousIndices = (Queue<string>)HttpContext.Current.Items[collectionIndexFieldName];
  112.  
  113.             if (previousIndices == null)
  114.  
  115.             {
  116.  
  117.                 HttpContext.Current.Items[collectionIndexFieldName] = previousIndices = new Queue<string>();
  118.  
  119.                 string previousIndicesValues = HttpContext.Current.Request[collectionIndexFieldName];
  120.  
  121.                 if (!string.IsNullOrWhiteSpace(previousIndicesValues))
  122.  
  123.                 {
  124.  
  125.                     foreach (string index in previousIndicesValues.Split(','))
  126.  
  127.                     {
  128.  
  129.                         previousIndices.Enqueue(index);
  130.  
  131.                     }
  132.  
  133.                 }
  134.  
  135.             }
  136.  
  137.             return previousIndices.Count > 0 ? previousIndices.Dequeue() : Guid.NewGuid().ToString();
  138.  
  139.         }
  140.  
  141.     }
  142.  
  143. }
  144.  

其原理,请参考"MVC批量更新,可验证并解决集合元素不连续控制器接收不完全的问题"这篇文章。

Home/RealGoTo.cshtml视图,是点击"到别的地方转转"后跳转到的页面,仅仅提供了一个跳转到Home/Index视图页的链接。

  1. @{
  2.  
  3.     ViewBag.Title = "RealGoTo";
  4.  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";
  6.  
  7. }
  8.  
  9. <h2>RealGoTo</h2>
  10.  
  11. @Html.ActionLink("回到表单页","Index","Home")
  12.  

就这样。

ASP.NET MVC中使用Session来保持表单的状态的更多相关文章

  1. ASP.NET MVC中的Session设置

    最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...

  2. ASP.NET MVC中的Session以及处理方式

    最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...

  3. ASP.NET MVC 中解决Session,Cookie等依赖的方式

    原文:https://blog.csdn.net/mzl87/article/details/90580869 本文将分别介绍在MVC中使用Filter和Model Binding两种方式来说明如何解 ...

  4. 转载ASP.NET MVC中Session的处理机制

    本文章转载自 http://www.cnblogs.com/darrenji/p/3951065.html ASP.NET MVC中的Session以及处理方式   最近在ASP.NET MVC项目中 ...

  5. ASP.NET MVC中的两个Action之间值的传递--TempData

    一. ASP.NET MVC中的TempData 在ASP.NET MVC框架的ControllerBase中存在一个叫做TempData的Property,它的类型为TempDataDictiona ...

  6. Asp.net MVC中提交集合对象,实现Model绑定

    Asp.net MVC中的Model自动绑定功能,方便了我们对于request中的数据的处理, 从客户端的请求数据,自动地以Action方法参数的形式呈现.有时候我们的Action方法中想要接收数组类 ...

  7. Asp.net MVC中 Controller 与 View之间的数据传递

    在ASP.NET MVC中,经常会在Controller与View之间传递数据 1.Controller向View中传递数据 (1)使用ViewData["user"] (2)使用 ...

  8. Asp.net mvc中的Ajax处理

    在Asp.net MVC中的使用Ajax, 可以使用通用的Jquery提供的ajax方法,也可以使用MVC中的AjaxHelper. 这篇文章不对具体如何使用做详细说明,只对于在使用Ajax中的一些需 ...

  9. 在ASP.NET MVC中实现基于URL的权限控制

    本示例演示了在ASP.NET MVC中进行基于URL的权限控制,由于是基于URL进行控制的,所以只能精确到页.这种权限控制的优点是可以在已有的项目上改动极少的代码来增加权限控制功能,和项目本身的耦合度 ...

随机推荐

  1. linux usb枚举过程分析之守护进程及其唤醒【转】

    转自:http://blog.csdn.net/xuelin273/article/details/38646765 usb热插拔,即usb设备可以实现即插即用,像U盘一样,插到电脑里就可以用,不用时 ...

  2. ajax与302响应

    在ajax请求中,如果服务器端的响应是302 Found,在ajax的回调函数中能够获取这个状态码吗?能够从Response Headers中得到Location的值进行重定向吗?让我们来一起看看实际 ...

  3. sonar Lint ----code bad smell

    类名注释报黄: 去掉这段黄做法:alt+enter 本文参考: http://www.cnblogs.com/xxoome/p/6677170.html

  4. snmp信息的查询命令snmpwalk

    在日常监控中,经常会用到 snmp 服务,而 snmpwalk 命令则是测试系统各种信息最有效的方法,现总结一些常用的方法如下: 获取所有信息snmpwalk -v 2c -c public 52.0 ...

  5. CSS3实现图片木桶布局

    CSS3实现图片木桶布局 效果图: 代码如下,复制即可使用: <!DOCTYPE html> <script> window.navigator.appVersion.inde ...

  6. liunx jdk安装

    打开https://www.oracle.com/technetwork/java/javase/downloads/index.html 选择Development版本(server为服务器版本), ...

  7. 神奇的Content-Type--在JSON中玩转XXE攻击

    转自:360安全播报http://bobao.360.cn/learning/detail/360.html 大家都知道,许多WEB和移动应用都依赖于Client-Server的WEB通信交互服务.而 ...

  8. 阿里云url解析,发布web后去除url中的端口号

    归根结底就是80端口的使用,不是http的80 的 或 https的  都得加端口号 [问题描述] http://wisecores.wisers.com:8080/JsonProject/servl ...

  9. [图解算法] 二分查找Binary-Search——<递归与分治策略>

    #include"iostream.h" int BinarySearch(int a[],int left,int right,const int& x) { if(le ...

  10. 在win7_64bit + ubuntu-12.04-desktop-amd64+VMware-workstation-full-10.0.1-1379776平台上安装ns-allinone-2.35

    step1.  ns-allinone-2.35的下载地址:http://www.isi.edu/nsnam/ns/ns-build.html#allinone step2.  在虚拟机中打开term ...