Sample Code - Use ASP.NET MVC With Razor

2015/10/312 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Razor Views
  3. Define the Page Data Class
  4. Populate Page Data
  5. Handle All Page Data in One Action
  6. Conclusion

Introduction

This post demonstrates how to use a single ASP.NET MVC action to handle multiple page data using Razor ViewBag. By defining a page data model, you can dynamically serve different content for different URLs through one controller action.

Razor Views

// index.cshtml

@{
    ViewBag.Title = "Index";
}

@ViewBag.Data1

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

@ViewBag.Test2

Define the Page Data Class

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

Populate Page Data

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

Handle All Page Data in One Action

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

Conclusion

This approach allows you to manage multiple pages through a single controller action by defining page data in a structured model. It keeps your controllers clean and makes it easy to add new pages without creating additional actions.