Click here to Skip to main content
15,884,473 members
Articles / Web Development / ASP.NET

Creating your own MVC View Engine For MVC Application

Rate me:
Please Sign up or sign in to vote.
4.47/5 (12 votes)
4 Dec 2011CPOL2 min read 99.8K   2K   29  
Implement your own MVC View Engine into MVC application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text.RegularExpressions;

namespace CustomMVCViewEngine
{
    public class MyView : IView
    {
        private string _viewPhysicalPath;

        public MyView(string ViewPhysicalPath)
        {
            _viewPhysicalPath = ViewPhysicalPath;
        }

        #region IView Members

        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);
        }

        #endregion

        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;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I have been working as a Software Engineer on Microsoft .NET Technology.I have developed several web/desktop application build on .NET technology .My point of interest is Web Development,Desktop Development,Ajax,Json,Jquey,XML etc.I have completed Master of Computer Application in May-2011.I'm not happy unless I'm learning something new.

Comments and Discussions