標籤: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 提交成功!