当我们使用jQuery异步提交表单数据的时候,需要把部分视图转换成字符串(带验证信息),以json的形式传递给前端视图。

 

使用jQuery异步加载部分视图,返回内容追加到页面某个div:

 

jQuery异步提交失败,返回带验证失败信息的部分视图字符串,并追加到页面div:

 

jQuery异步提交成功,返回显示提交成功的部分视图字符串,并追加到页面div:

 

一个简单的Model:

using System.ComponentModel.DataAnnotations;
 
namespace MvcApplication1.Models
{
    public class Pet
    {
        public int Id { get; set; }
 
        [Display(Name = "宠物")]
        [Required(ErrorMessage = "必填")]
        public string Name { get; set; }
    }
}
 

.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; }

扩展控制器,把部分视图内容转换成字符串。

using System.IO;
 
namespace System.Web.Mvc
{
    public static class ControllerExtensions
    {
        //根据部分视图名称,把部分视图内容转换成字符串
        public static string RenderPartialViewToString(this Controller controller, string partialViewName)
        {
            return controller.RenderPartialViewToString(partialViewName, null);
        }
 
        //根据部分视图名称和model,把部分视图内容转换成字符串
        public static string RenderPartialViewToString(this Controller controller, string partialViewName, object model)
        {
            //如果partialViewName为空,就把action名称作为部分视图名称
            if (string.IsNullOrEmpty(partialViewName))
            {
                partialViewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }
 
            //把model放到Controller.ViewData.Model属性中
            controller.ViewData.Model = model;
 
            using (var sw = new StringWriter())
            {
                //通过视图引擎,在当前ControllerContext中,根据部分视图名称获取ViewEngineResult类型
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName);
 
                //创建ViewContext
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData,
                    controller.TempData, sw);
 
                //把内容写到StringWriter中
                viewResult.View.Render(viewContext, sw);
 
                //StringWriter→string
                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
 

.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; }

Home/Index.cshtml视图,提交之前,以异步Get方式请求部分视图的html内容;点击提交,以异步Post方式请求从控制器返回的部分视图字符串内容。

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<div id="petContent">
</div>
<div>
    <input type="button" id="btn" value="提交"/>
</div>
 
@section scripts
{
    <script type="text/javascript">
        $(function() {
            init();
 
            //提交
            $('#btn').click(function() {
                $.ajax({
                    cache: false,
                    url: '@Url.Action("SaveData", "Home")',
                    type: "POST",
                    data: $('#addForm').serialize(),
                    success: function (data) {
                        $('#petContent').empty();
                        $('#petContent').append(data.message);
                    },
                    error: function (jqXhr, textStatus, errorThrown) {
                        alert("出错了 '" + jqXhr.status + "' (状态: '" + textStatus + "', 错误为: '" + errorThrown + "')");
                    }
                 });
            });
        });
 
        function init() {
            $.ajax({
                cache: false,
                url: '@Url.Action("GetPet", "Home")',
                contentType: 'application/html;charset=utf-8',
                type: "GET",
                success: function(result) {
                    $('#petContent').append(result);
                },
                error: function(xhr, status) {
                    alert("加载内容失败" + status);
                }
            });
        }
    </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; }

 

HomeController部分:

using System.Web.Mvc;
using MvcApplication1.Models;
 
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //主页面
        public ActionResult Index()
        {
            return View();
        }
 
        //接收异步Get请求,部分视图以html返回给前端视图
        public ActionResult GetPet()
        {
            return PartialView();
        }
 
        //接收异步Post请求,部分视图转换成字符串,以json返回给前端视图
        [HttpPost]
        public ActionResult SaveData(Pet pet)
        {
            if (ModelState.IsValid)
            {
                //TODO: insert into database
                return Json(new {msg = true, message = this.RenderPartialViewToString("Success", pet)});
            }
            return Json(new { msg = false, message = this.RenderPartialViewToString("GetPet", pet) });
        }
    }
}
 

.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; }

 

Home/GetPet.cshtml部分视图:

@model MvcApplication1.Models.Pet
 
@using (Html.BeginForm("SaveData", "Home", FormMethod.Post, new {id = "addForm"}))
{
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
}

.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; }

 

Home/Success.cshtml部分视图:

@model MvcApplication1.Models.Pet
 
@Model.Name 提交成功!

.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; }

MVC扩展控制器, 把部分视图转换成字符串(带验证信息), 并以json传递给前端视图的更多相关文章

  1. 前台 JSON对象转换成字符串 相互转换 的几种方式

    在最近的工作中,使用到JSON进行数据的传递,特别是从前端传递到后台,前台可以直接采用ajax的data函数,按json格式传递,后台Request即可,但有的时候,需要传递多个参数,后台使用requ ...

  2. 基于Visual C++2013拆解世界五百强面试题--题4-double转换成字符串

    请用C语言实现将double类型数据转换成字符串,再转换成double类型的数据.int类型的数据 想要完成题目中的功能,首先我们的先对系统存储double的格式有所了解. 浮点数编码转换使用的是IE ...

  3. 如何将javascript对象转换成字符串

    将后台程序(如php)发送过来的json数据转化为javascript的数组或者对象的方法十分简单,代码如下: 1 // 假设后台发送的json数据为 '{a:2,b:1}' 存储于str中 2 va ...

  4. C#字节数组转换成字符串

    C#字节数组转换成字符串 如果还想从 System.String 类中找到方法进行字符串和字节数组之间的转换,恐怕你会失望了.为了进行这样的转换,我们不得不借助另一个类:System.Text.Enc ...

  5. 100怎么变成100.00 || undefined在数字环境下是:NaN || null在数字环境下是0 || 数组的toString()方法把每个元素变成字符串,拼在一起以逗号隔开 || 空数组转换成字符串后是什么?

    100怎么变成100.00?

  6. 怎样把php数组转换成字符串,php implode()

    实例代码 一维数组转换成字符串代码! <?php $arr1=array("shu","zhu","1"); $c=implode(& ...

  7. Javascript里,想把一个整数转换成字符串,字符串长度为2

    Javascript里,想把一个整数转换成字符串,字符串长度为2.  想把一个整数转换成字符串,字符串长度为2,怎么弄?比如 1 => "01"11 => " ...

  8. Android 读取txt文件并以utf-8格式转换成字符串

    博客: 安卓之家 微博: 追风917 CSDN: 蒋朋的家 简书: 追风917 博客园: 追风917 # 使用EncodingUtils 今天用到了城市选择三级联动的库,用的这个:https://gi ...

  9. 在Ajax中将数组转换成字符串(0517-am)

    一.如何在Ajax中将数组转换成字符串 1. 主页面; <head> <meta http-equiv="Content-Type" content=" ...

随机推荐

  1. KDE 下 U 盘挂载失败

    重装完 KDE 后发现在 dolphin 中无法挂载 U 盘了,提示 unable to authenticate.但是用 udisksctl 却可以挂载: yyc@TDesk run > ud ...

  2. 如何适配处理iphoneX底部的横条 - ios

    iphoneX手机取消了实体Home键,取而代之的是主界面底部不显眼的横条“Home Indicator”.当网页底部fixed 元素时候,一部分元素可能就被这个横条遮挡住,怎么适配解决呢? 第一步: ...

  3. Java之杨辉三角的实现

    今天突然想温习一下Java的基础,想了想就写写杨辉三角吧 1.直接法,利用二维数组 import java.util.Scanner; public class Second { public sta ...

  4. Visual Studio 2013百度云下载地址

    Visual Studio 2013百度云下载地址: 链接: https://pan.baidu.com/s/1JkVYLnFo2TWSu4dkDdZP3Q  提取码: 关注公众号[获取   winf ...

  5. Storm(二)CentOS7.5搭建Storm1.2.2集群

    一.Storm的下载 官网下载地址:http://storm.apache.org/downloads.html 这里下载最新的版本storm1.2.2,进入之后选择一个镜像下载 二.Storm伪分布 ...

  6. jquery实现checkbox的单选和全选

    一.思路 全选:判断“全选”checkbox的状态,如果选中则把tbody下所有的checkbox选中,反之 单选:主要是判断有没有全选,如果不是选中状态就把全选的checkbox状态设置为false ...

  7. shell如何向python传递参数,shell如何接受python的返回值

    1.shell如何向python传递参数 shell脚本 python $sendmailCommandPath $optDate python脚本 lastDateFormat = sys.argv ...

  8. CSUOJ 1008 Horcrux

    Description A Horcrux is an object in which a Dark wizard or witch has hidden a fragment of his or h ...

  9. 交换机高级特性MUX VLAN

    MUX VLAN 基本概念 lMUX VLAN(Multiplex VLAN)提供了一种通过VLAN进行网络资源控制的机制. 例如,在企业网络中,企业员工和企业客户可以访问企业的服务器. 对于企业来说 ...

  10. [ 原创 ]学习笔记-Android 中关于Cursor类的介绍

    此博文转载自:http://www.cnblogs.com/TerryBlog/archive/2010/07/05/1771459.html 主讲Cursor的用法 使用过 SQLite 数据库的童 ...