Sample Code - Use ASP.NET MVC With Razor

2015/10/312 min read
bookmark this
Responsive image

// index.cshtml

@{
    ViewBag.Title = "Index";
}

@ViewBag.Data1


// test.cshtml
@{
    ViewBag.Title = "Test2";
}

@ViewBag.Test2


// define the class for page data
 public class AllPage
    {
        public AllPage()
        {
            Pages = new List();
        }

        public List Pages { get; set; }
    }

    public class Page
    {
        public Page()
        {
            PageData = new List();
        }

        public string RequestUrl { get; set; }
        public string RazorName { get; set; }
        public List PageData { get; set; }
    }

    public class PageData
    {
        public string TmplName { get; set; }
        public string TmplValue { get; set; }
    }

// get page data
 private AllPage _page;
        public HomeController()
        {
            AllPage pages = new AllPage();
            pages.Pages.Add(new Page 
            {
                 RequestUrl = "/",
                 RazorName = "Index",
                 PageData = new List { new PageData
                 {
                       TmplName = "Data1",
                        TmplValue = "Index.Data1.Value1"
                 }}
            });

            pages.Pages.Add(new Page
            {
                RequestUrl = "/Test2",
                RazorName = "Test2",
                PageData = new List { new PageData
                 {
                       TmplName = "Test2",
                       TmplValue = "Test2.Data1.Value1"
                 }}
            });
            _page = pages;
        }

// handler all page data in one action
 public ActionResult Index()
        {
            var requestUrl = Request.Url.AbsolutePath;
            var page =_page.Pages.Where(x => x.RequestUrl.Equals(requestUrl, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            if (page == null)
            {
                // go to 404 page
                return View();
            }

            page.PageData.ForEach(_ => 
            {
                ViewData.Add(_.TmplName, _.TmplValue);
            });

            return View(page.RazorName);
        }