您可以使用此答案RenderPartialViewToString
中显示的方法将视图呈现为字符串,然后返回您编写的自定义 JsonpResult:
public class StudentsController : Controller
{
public ActionResult Index()
{
MyViewModel model = ...
return new JsonpResult(new
{
html = RenderViewToString("Index", model)
});
}
public string RenderViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = ControllerContext.RouteData.GetRequiredString("action");
}
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
这里使用的JsonpResult
类可以在这篇文章中找到。
现在您可以使用来自另一个域的 AJAX 调用此控制器操作:
var url = 'http://example.com/students/index';
$.getJSON(url + '?callback=?', function (data) {
alert(data.html);
});