2

I need to acquire HTML markup of a controller/action in order to generate PDF. What I have done is:

    public ActionResult Index()
    {
        Session["Message"] = "SESSION-MESSAGE";

        String URL = "http://localhost:7401/Home/SuperComplex";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
        req.CookieContainer = new CookieContainer();

        for (int i = 0; i <= this.Request.Cookies.Count - 1; i++)
            req.CookieContainer.Add(
                new System.Net.Cookie(
                    name: this.Request.Cookies[i].Name,
                    value: Request.Cookies[i].Value,
                    path: Request.Cookies[i].Path, domain: this.HttpContext.Request.Url.Host)
                );

        using (var r = req.GetResponse())
        {
            using (var s = new StreamReader(r.GetResponseStream()))
            {
                var htmlToPrint = s.ReadToEnd();
                Response.Write("<h1>" + htmlToPrint + "</h1>");
            }
        }

        return View();
    }

Considering above said situation, in SuperComplex session, I should have the Session["Message"]. But for some strange reason, it does not go there.

I have checked Session.SessionId - in both cases it is same.

Also, on second or third request, request timesout!

Again: http://localhost:7401/(S(SESSION_ID))/Home/About

If requested in other browser: session hijack does happen - but WebRequest dies! :(

Help - anyone?

4
  • Is it specific to ASP.NET MVC 4 (which is in Beta now)? If so, change the tag to asp.net-mvc-4. If not, change your question's title. Commented Feb 20, 2012 at 19:05
  • Thanks Ofer - fixed tht title. Commented Feb 20, 2012 at 19:06
  • You are not using a webrequest to get the html from your own website aren't you? There are better means for this. Commented Feb 20, 2012 at 20:01
  • @usr: yes, I am trying to do so.. :(.. any specific mean you would like to mention? Commented Feb 20, 2012 at 20:08

1 Answer 1

2

Store your HTML in a Partial View and then use a Helper function to parse it into a string.

// usage
/*
 * http://stackoverflow.com/questions/4344533/asp-net-mvc-razor-how-to-render-a-razor-partial-views-html-inside-the-controll
 * 
    var model = _repository.Find(x => x.PropertyID > 3).FirstOrDefault();
    var test = this.RenderViewToString("DataModel", model);
    return Content(test);
 */

public static string RenderPartialToString<T>(this ControllerBase controller, string partialName, T model)
{
    var vd = new ViewDataDictionary(controller.ViewData);
    var vp = new ViewPage
    {
        ViewData = vd,
        ViewContext = new ViewContext(),
        Url = new UrlHelper(controller.ControllerContext.RequestContext)
    };

    ViewEngineResult result = ViewEngines
                              .Engines
                              .FindPartialView(controller.ControllerContext, partialName);

    if (result.View == null)
    {
        throw new InvalidOperationException(
        string.Format("The partial view '{0}' could not be found", partialName));
    }
    var partialPath = ((RazorView)result.View).ViewPath;

    vp.ViewData.Model = model;

    using(StringWriter sw = new StringWriter()) {
        ViewContext viewContext = new ViewContext(controller.ControllerContext, result.View, vd, controller.TempData, sw);
        result.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yea, I did that and moved forward. Thanks for posting reply - maybe someone else can benefit from it :). Cheers;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.