页面静态化(nVelocity)

百度上,nVelocity 的简介是:

       当nVelocity 应用于web开发时,界面设计人员可以和.NET程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只关注页面的显示效果,而由.NET程序开发人员关注业务逻辑编码。

       使用的时候,首先写一个公共类:

using NVelocity;
    using NVelocity.App;
    using NVelocity.Runtime;

namespace web
{
    public class DetailHelper
    {
        public static string RenderHtml(string name, object data)
        {
            VelocityEngine vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/Temppates"));//模板文件所在的文件夹
            vltEngine.Init();
            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("Model", data);//设置参数,在模板中可以通过$data来引用
            Template vltTemplate = vltEngine.GetTemplate(name);
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            return vltWriter.GetStringBuilder().ToString();
        }

    }
}

在.ashx中,添加以下方法:

 HttpContext ht;
    StreamWriter sw = null;
public class Handler : IHttpHandler
{
    HttpContext ht;
    StreamWriter sw = null;
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        ht = context; string html; string fileName;
        var data = new { title = "专家", Cont = BindPage(), cssstyleback = "body-expert" };//BindPage()这个方法用来绑定前台的页面数据
        html = web.DetailHelper.RenderHtml("expert.html", data);
        //context.Response.Write(html);
        fileName = "expert.html";
        try
        {
            string path = HttpContext.Current.Request.MapPath("/生成的html文件夹/");
            sw = new StreamWriter(path + fileName, false, System.Text.Encoding.UTF8);
            sw.Write(html);
            sw.Flush();
            context.Response.Write("1");
        }
        catch (Exception ex)
        {
            context.Response.Write("{\"result\":\"0\" ,\" mes \" :\" " + ex.Message + "\"}");
        }
        finally
        {
            if (sw != null)
            {
                sw.Close();
            }
        }
    }
}

在html页面中,添加如下代码:
#parse("top.html")
  
    #foreach($rpt_zjtd in $Model.rpt_zjtd)
  • $rpt_zjtd.Field_01

    $rpt_zjtd.Field_04
    擅长:

    $rpt_zjtd.Field_05

  • #end
#parse("bottom.html")
其中,头尾是添加的html的引用


你可能感兴趣的:(C#代码)