对字符串的部分视图 - 用于电子邮件内容等
调用函数
string InvoiceHtml = myFunction.RenderPartialViewToString("PartialInvoiceCustomer", ToInvoice); // ToInvoice is a model, you can pass parameters if needed
生成 HTML 的功能
public static string RenderPartialViewToString(string viewName, object model)
{
using (var sw = new StringWriter())
{
BuyOnlineController controller = new BuyOnlineController(); // instance of the required controller (you can pass this as a argument if needed)
// Create an MVC Controller Context
var wrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", controller.GetType().Name.ToLower().Replace("controller", ""));
controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
controller.ViewData.Model = model;
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.ToString();
}
}
部分视图 - PartialInvoiceCustomer
@model eDurar.Models.BuyOnlineCartMaster
<h2>hello customer - @Model.CartID </h2>