How to render an ASP.NET MVC view as a string?

后端 未结 15 2914
挽巷
挽巷 2020-11-21 04:40

I want to output two different views (one as a string that will be sent as an email), and the other the page displayed to a user.

Is this possible in ASP.NET MVC bet

15条回答
  •  死守一世寂寞
    2020-11-21 04:51

    you are get the view in string using this way

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");
    
        if (model != null)
            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();
        }
    }
    

    We are call this method in two way

    string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", null)
    

    OR

    var model = new Person()
    string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", model)
    

提交回复
热议问题