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

后端 未结 15 2972
挽巷
挽巷 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 05:18

    I found a better way to render razor view page when I got error with the methods above, this solution for both web form environment and mvc environment. No controller is needed.

    Here is the code example, in this example I simulated a mvc action with an async http handler:

        /// 
        /// Enables processing of HTTP Web requests asynchronously by a custom HttpHandler that implements the IHttpHandler interface.
        /// 
        /// An HttpContext object that provides references to the intrinsic server objects.
        /// The task to complete the http request.
        protected override async Task ProcessRequestAsync(HttpContext context)
        {
            if (this._view == null)
            {
                this.OnError(context, new FileNotFoundException("Can not find the mvc view file.".Localize()));
                return;
            }
            object model = await this.LoadModelAsync(context);
            WebPageBase page = WebPageBase.CreateInstanceFromVirtualPath(this._view.VirtualPath);
            using (StringWriter sw = new StringWriter())
            {
                page.ExecutePageHierarchy(new WebPageContext(new HttpContextWrapper(context), page, model), sw);
                await context.Response.Output.WriteAsync(sw.GetStringBuilder().ToString());
            }
        }
    

提交回复
热议问题