MVC擴充控制器, 把部分視圖轉換成字串(帶驗證資訊), 並以json傳遞給前端視圖

來源:互聯網
上載者:User

標籤:style   c   class   blog   code   java   

當我們使用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; }
    }
}
 

擴充控制器,把部分視圖內容轉換成字串。

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();
            }
        }
    }
}
 

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

 

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

 

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)
}

 

Home/Success.cshtml部分視圖:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.