开发者

How can I use asp.net to generate and return an HTML document as a string (outside of a web context)

I need to write 开发者_StackOverflowa system to generate HTML email from a data model -

I was going to create a templating system to build the model into an HTML representation using HTML 'fragments' stored in an xml template. But it occurs to me that these it might be better to use asp or asp.net than write my own templating system?

What I am wondering is whether/how it would be possible to use asp (maybe asp.net mvc?) to return an HTML string - I wouldn't be running on a web server, or in response to an HTTP request.

I have not done any asp or asp.net yet- My experience of ASP stretches to 'Create new project' in visual studio - but maybe now is a good time to learn!

Thank You!


The standard ASP.NET view engine--ASP.NET web forms--is very difficult to use in this way as it is pretty tied to the HttpContext and really don't want to give you a string back but rather stream into the HttpResponse. So you'd generally need IIS stood up to get it to go.

Xslt (as you are thinking) is a pretty decent option. As is, if things are simple enough, your own template replacement scheme. Now, if things are complex enough, some other options would include:

  • The Spark View Engine
  • The new Asp.NET Razor View Engine.

Either of those should let you get a string out of a template without too much trouble.


The simplest way is to make an aspx page that renders the email and then read it on the server using WebClient or and HttpWebRequest.

System.Net.WebClient oClient = new System.Net.WebClient();
string Email = oClient.DownloadString(UrlOfPage);

There are other ways to capture the output and I am sure if you search on Google you can find articles about this, but from personal experience this is the simplest way to go.

Also beware of the Html/Css limitations of many email clients. It is not the same as a browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜