How to make Custom View Engine?

ASP.NET MVC is an open source and highly extensible framework. You can create your own View engine by Implementing IViewEngine interface or by inheriting VirtualPathProviderViewEngine abstract class.

public class CustomViewEngine: VirtualPathProviderViewEngine {
    public CustomViewEngine() { // Define the location of the View and Partial View
        this.ViewLocationFormats = new string[] {
            "~/Views/{1}/{0}.html", "~/Views/Shared/{0}.html"
        };
        this.PartialViewLocationFormats = new string[] {
            "~/Views/{1}/{0}.html", "~/Views/Shared/{0}.html"
        };
    }
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
        return new CustomView(physicalpath);
    }
    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
        return new CustomView(physicalpath);
    }
}
public class CustomView: IView {
    private string _viewPhysicalPath;
    public CustomView(string ViewPhysicalPath) {
        _viewPhysicalPath = ViewPhysicalPath;
    }
    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        //Load File
        string rawcontents = File.ReadAllText(_viewPhysicalPath);
        //Perform Replacements
        string parsedcontents = Parse(rawcontents, viewContext.ViewData);
        writer.Write(parsedcontents);
    }
    public string Parse(string contents, ViewDataDictionary viewdata) {
        return Regex.Replace(contents, "\\{(.+)\\}", m => GetMatch(m, viewdata));
    }
    public virtual string GetMatch(Match m, ViewDataDictionary viewdata) {
        if (m.Success) {
            string key = m.Result("$1");
            if (viewdata.ContainsKey(key)) {
                return viewdata[key].ToString();
            }
        }
        return string.Empty;
    }
}

 

Tagged , . Bookmark the permalink.

Leave a Reply