mvc-自定义视图引擎

//自定义视图引擎的实质是把数据模型(moudle)和模板(View)转换成html页面,输出到客户端
public
class MyView:IView { string _viewPath; public MyView(string viewPath) { this._viewPath = viewPath; } public void Render(ViewContext viewContext, System.IO.TextWriter writer) { // 获取视图文件的原始内容 string rawContents = File.ReadAllText(_viewPath); // 根据自定义的规则解析原始内容 string parsedContents = Parse(rawContents, viewContext.ViewData); // 呈现出解析后的内容 writer.Write(parsedContents); } private string Parse(string contents,ViewDataDictionary viewData) { // 对 {##} 之间的内容作解析 return Regex.Replace ( contents, @"\{#(.+)#\}", p => GetMatch(p, viewData) ); } protected virtual string GetMatch(Match m, ViewDataDictionary viewData) { if (m.Success) { // 获取匹配后的结果,即 ViewData 中的 key 值,并根据这个 key 值返回 ViewData 中对应的 value string key = m.Result("$1"); if (viewData.ContainsKey(key)) { return viewData[key].ToString(); } } return string.Empty; } } public class MyViewEngine:VirtualPathProviderViewEngine { public MyViewEngine() { //自定义View路径格式 base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.my", "~/Views/Shared/{0}.my" }; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return this.CreateView(controllerContext, partialPath, string.Empty); }
     //把请求转换成
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { var physicalPath = controllerContext.HttpContext.Server.MapPath(viewPath); return new MyView(physicalPath); } }

 

你可能感兴趣的:(mvc)