Question

I have got an ASP.net MVC project and admittedly I'm not too interested in the way MS implements MVC and so have stripped the project to the very bare minimum. I don't have any routes defined and instead have a DefaultDocument entry in web.config that points to a class that implements IHttpHandler.

From my IHttpHandler class, I'm wanting to output a Razor .cshtml file, I do not wish to create route entries to the cshtml files and so I cannot simply redirect the user to the .cshtml file. I've found a number of resources talking about PageParser.GetCompiledPageInstance but this appears to be aimed at aspx files rather than the Razor View Engine.

So, what classes should be of interest to me in outputting a .cshtml file to the HttpContext from my IHttpHandler class?

public class Main : IHttpHandler{
    public void ProcessRequest(HttpContext context){
        //
    }
}
Was it helpful?

Solution

It appears I have been looking for the wrong thing - the secret phrase is:

Rendering razor view to a string

The code below works quite well it would seem:

public static string GetRazorViewAsString(object model, string filePath)
{
    var st = new StringWriter();
    var context = new HttpContextWrapper(HttpContext.Current);
    var routeData = new RouteData();
    var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController());
    var razor = new RazorView(controllerContext, filePath, null, false, null);
    razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st), st);
    return st.ToString();
}

Code from http://forums.asp.net/post/5333141.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top