这是一些将起作用的代码,因为我今天需要这样做。原始代码在这里描述。
public static string RenderPartialToString(string controlName, object viewData){ var viewContext = new ViewContext(); var urlHelper = new UrlHelper(viewContext.RequestContext); var viewDataDictionary = new ViewDataDictionary(viewData); var viewPage = new ViewPage { ViewData = viewDataDictionary, ViewContext = viewContext, Url = urlHelper }; var control = viewPage.LoadControl(controlName); viewPage.Controls.Add(control); var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) using (var tw = new HtmlTextWriter(sw)) { viewPage.RenderControl(tw); } return sb.ToString();}
然后,您可以使用它来执行RJS样式的json结果
public virtual ActionResult Index(){ var jsonResult = new JsonResult { Data = new { main_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()), secondary_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()), } }; return Json(jsonResult, JsonRequestBehavior.AllowGet);}
并且局部具有强类型视图模型
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeObject>" %><h1>My Partial</h1>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)