views:

62

answers:

2

This may be a bad idea for any number of reasons, but I still want to accomplish it. Is there a way to render a view from a string that contains some HTML and code blocks? My initial thought is that I would implement IView and have that take the HTML string in the constructor. Then pass it to the View method along with the model, like so:

public ActionResult MyAction() {
    var str = @"<html><body><%= Model.SomeProperty %></body></html>";
    var myView = new MyIView(str);
    return View(myView, Model);
}

At this point I get a little stuck since I don't know how to invoke the view engine to parse the string and make it all work. Or, at this point, do I have to parse and render it myself?

+2  A: 

Unfortunately, this is not easy to do for ASPX pages.

In ASP.Net Razor, it's much easier.

If you really want to do it, register a custom VirtualPathProvider that resolves special paths to your strings, then call BuildManager.CreateInstanceFromVirtualPath, cast it to ViewPage, set its ViewData, and call RenderView.

SLaks
To add to SLaks answer, if all you want to do is hard code some return value in your controller then you can just build your string manually: `var str = @"<html><body>" + Model.SomeProperty + @"</body></html>"`. However if what you actually want to do is store your views in a database (instead of as a file) then you will have to implement a VirtualPathProvider that returns the contents of your database for requests to a particular path.
marcind
I have implemented a `VirtualPathProvider`, and it's working great, with one exception. The views served are unable to use a strongly typed Model. I always get `Could not load type 'System.Web.Mvc.ViewPage<Model>'.` Any ideas?
Freyday
@Freyday: Change your `VirtualPathProvider` to provide your actual `bin` directory (which contains the compiled DLL with your model class).
SLaks
A: 

You can just return string in your action.

public string MyAction() {
    return @"<html><body>" + Model.SomeProperty + @"</body></html>";
}
Ryan
This really isn't the type of solution I'm looking for. The example included in the original question has been simplified to illustrate what I'm trying to accomplish.
Freyday