需求:
有時候使用Ajax有return PartialView的需求,但卻又只能傳送Json,不能return PartialView,這時候就只能把想回傳的view 轉成字串了。
實作:
Index:
我們簡單寫一個頁面,裡面有一個button,並寫一個click事件,在按下之後會在TOP與BOTTOM div之前回傳我們所想加入的view。
<div>
<button onclick="TestBtn()">回傳patrialView</button>
</div>
<div>TOP</div>
<div id="PartialDiv"></div>
<div>BOTTOM</div>
@Html.Hidden("TestViewUrl",Url.Action("TestViewToString", "Home"))
@section scripts{
<script>
function TestBtn() {
$.ajax({
url: $('#TestViewUrl').val(),
type: "POST",
success: function (e) {
$('#PartialDiv').html(e.TestView);
},
error: function (e) {
console.log(e);
alert(e);
}
})
}
</script>
}
partialView:
partialView的部分我們簡單實作一個model是string類型,並有一個viewData
@model string
@{ var viewData = (string)ViewData["TestViewData"];}
<h2>Model: @Model ViewData: @viewData</h2>
controller:
簡單寫一個action來回傳view,主要要注意的是ConvertViewToString()這個方法,來將view轉成string
public ActionResult TestViewToString()
{
string model = "我是model";
ViewData["TestViewData"] = "我是ViewData";
return Json(new
{
TestView = ConvertViewToString("_TestPartial", model, ViewData)
});
}
/// <summary>
/// 轉換View To String
/// </summary>
/// <param name="viewName">View名稱</param>
/// <param name="model">model</param>
/// <param name="viewData">viewData</param>
/// <returns></returns>
private string ConvertViewToString(string viewName, object model = null, ViewDataDictionary viewData = null)
{
using (StringWriter writer = new StringWriter())
{
if (viewData == null)
{
ViewData.Model = model;
viewData = ViewData;
}
else
{
viewData.Model = model;
}
ViewEngineResult vResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext vContext = new ViewContext(this.ControllerContext, vResult.View, viewData, new TempDataDictionary(), writer);
vResult.View.Render(vContext, writer);
return writer.ToString();
}
}
結果:
留言
張貼留言