您可以在控制器中使用以下方法:
public string UpdateDivWithContent()
{
var yourModel = ... //make custom data to create your partial
return RenderPartialViewToString("YourPartialViewName", yourModel)
}
我将此方法放入基本控制器中:
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = ControllerContext.RouteData.GetRequiredString("action");
}
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
使用手动 ajax 调用从您的视图中调用此操作,例如:
$.ajax({
url: '@(Url.Action("UpdateDivWithContent","YourControllerName")'
type: 'POST',
data: {
//some params to be passed to the controller
},
success: function (result) {
//result is an html string of your customized partial view
$("#yourDivId").html(result);
}
});