将PartialView转换为HTML
我只是想知道是否有可能转换
PartialView("_Product", model)
到HTML,所以我们可以用JSON发回它?
return Json(result, JsonRequestBehavior.AllowGet);
当然,将以下方法放在共享控制器或辅助类中。 它将以HTML格式返回呈现的视图,用法是自解释的:
public static string RenderViewToString(ControllerContext context, string viewName, object model) { if (string.IsNullOrEmpty(viewName)) viewName = context.RouteData.GetRequiredString("action"); var viewData = new ViewDataDictionary(model); using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(context, viewName); var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw); viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString(); } }
我不知道这是不是最好的做法,但如果你把它保持原样
return PartialView("_Product", model)
然后你可以使用AJAX调用方法:
$.ajax ({ type: "POST", url: _url, data: _data, success: function (result) { // the result is the returned html from the partial view } })