How to Display Dynamic Content Inside Views

This article provides a brief idea of how to add dynamic content inside a view. Well there are various ways through which we can include dynamic content inside the view. The word dynamic means the content of the view is generated at runtime and it will be different for every request. Let's say on a shopping website, the customer is looking for the number of items he/she has added to the cart, in that case every customer will have a different view shown to him/her depending on the number of items he/she added to the cart. This is what we can say is dynamically showing of data. For displaying dynamic content on the view there are several approaches that can be used, some of them are:

  1. @if else or @switch case or @for or @foreach inside the view itself for doing a conditional construct, we can also call it inline code since it is written inside the view. This is for performing a simple conditional construct. We can call it as inline code.
  2. Partial Views: an analogy similar to including a user control inside a page. It offers code reusability by using the same piece of code wherever you require it. It has the same extension “.cshtml” and it is stored inside the ~/Views/shared folder so that the view can use it inside itself. Partial views can be either normal or strongly typed.
  3. Sections: a way to group/create a section that will be inserted in the layout at a specified region. It helps you to define a page like a template with a specific piece of code at a specific location. Sections can be divided into two types, in other words fixed section or optional section.
  4. HTML Helper Method: you can define your own HTML helper method. There are system-defined helper methods also that we use for creation of a control like an anchor.
  5. Child Actions: used for executing the action inside the main action.

Ok now let's start with the example; we'll try to create a simple demo for each of them. For this we will create a new project whose project template will be “basic” and no unit testing will be done so uncheck the checkbox for unit testing. I'm naming my project as “DynamicView”.

1. For Inline Code (@if else or @switch case or @foreach or @for)

Let's add a new controller to the application with the name “Home” and also add a new model with the name “Customer.cs”.

Here is the code snippet for the Model “Customer”:

  1. public enum CustomerType  
  2. {  
  3.     Regular = 0,  
  4.     FirstTime = 1,  
  5.     WindowShopper=2  
  6. }  
  7.   
  8. public class Customer  
  9. {  
  10.     public int CustID { getset; }  
  11.   
  12.     public string Name { getset; }  
  13.   
  14.     public string Address { getset; }  
  15.   
  16.     public CustomerType CustomerType { getset; }  

Also here we've added a new folder to the application with the name “Infrastructure” that contains a C# file with the name “SampleData.cs” that will provide Sample Data to our controller. Here is the code snippet for that:

  1. public static class SampleData  
  2. {  
  3. public static IEnumerable<Customer> GetDummyCustomer()  
  4. {  
  5. List<Customer> lstCutomers = new List<Customer>()  
  6. {  
  7. new Customer(){CustID=1,Name="Vishal",Address="Andheri",CustomerType=CustomerType.Regular},  
  8. new Customer(){CustID=2,Name="Rahul",Address="Dadar",CustomerType=CustomerType.FirstTime},  
  9. new Customer(){CustID=3,Name="Lincy",Address="Ghatkopar",CustomerType=CustomerType.WindowShopper},  
  10. new Customer(){CustID=4,Name="Mahesh",Address="Worli",CustomerType=CustomerType.FirstTime},  
  11. new Customer(){CustID=5,Name="Ollin",Address="Churchgate",CustomerType=CustomerType.Regular},  
  12. };  
  13. return lstCutomers;  
  14. }  

Inside the action Index method write the following block of lines:

  1. public class HomeController : Controller  
  2. {  
  3. public ActionResult Index()  
  4. {  
  5. return View(SampleData.GetDummyCustomer());  
  6. }  

Here is the snippet for Index.cshtml:

  1. @using DynamicView.Models  
  2. @model IEnumerable<Customer>  
  3. @{  
  4. ViewBag.Title = "Index";  
  5. }  
  6. <h2>  
  7. Index</h2>  
  8. <table>  
  9. <thead>  
  10. <tr>  
  11. <td>  
  12. Customer ID  
  13. </td>  
  14. <td>  
  15. Name  
  16. </td>  
  17. <td>  
  18. Address  
  19. </td>  
  20. <td>  
  21. Customer Type  
  22. </td>  
  23. </tr>  
  24. </thead>  
  25. <tbody>  
  26. @foreach (var cust in Model)  
  27. {  
  28. <tr>  
  29. <td>  
  30. @cust.CustID  
  31. </td>  
  32. <td>  
  33. @cust.Name  
  34. </td>  
  35. <td>  
  36. @cust.Address  
  37. </td>  
  38. <td>  
  39. @* @if (cust.CustomerType == CustomerType.Regular)  
  40. {  
  41. <font color="green">@cust.CustomerType</font>  
  42. }  
  43. else if (cust.CustomerType == CustomerType.FirstTime)  
  44. {  
  45. <font color="pink">@cust.CustomerType</font>  
  46. }  
  47. else  
  48. {  
  49. <font color="gray">@cust.CustomerType</font>  
  50. }*@  
  51. @switch (cust.CustomerType)  
  52. {  
  53. case CustomerType.Regular:  
  54. <font color="green">@cust.CustomerType</font>  
  55. break;  
  56. case CustomerType.FirstTime:  
  57. <font color="pink">@cust.CustomerType</font>  
  58. break;  
  59. default:  
  60. <font color="gray">@cust.CustomerType</font>  
  61. break;  
  62. }  
  63. </td>  
  64. </tr>  
  65. }  
  66. </tbody>  
  67. </table> 

Here is the snapshot of it.



2. Partial Views

We can create partial view as normal or as strongly typed views. For demonstrating this we'll just add a normal partial view that will provide us with a way to filter the customer's data by their name. For adding a partial view, click on the shared folder inside the view and add a new partial view by the name “FilterCustomer”. Here is the code snippet for the partial view.

  1. @using (Html.BeginForm("Filter""Home", FormMethod.Post, new { id = "filterForm" }))  
  2. {  
  3. <div style="width: 250px; background-color: White; color: #0e0e6c;">  
  4. <table>  
  5. <caption>  
  6. Filter By Name</caption>  
  7. <tr>  
  8. <td>  
  9. Name:  
  10. </td>  
  11. <td>  
  12. <input type="text" name="custName" value="@ViewBag.CustomerName" />  
  13. </td>  
  14. </tr>  
  15. <tr>  
  16. <td>  
  17. <input type="submit" value="Filter" id="btnFilter" name="btnSubmit" />  
  18. </td>  
  19. <td>  
  20. <input type="submit" value="Clear Filter" id="btnClear" name="btnSubmit" />  
  21. </td>  
  22. </tr>  
  23. </table>  
  24. </div>  

Also we've added a new function to our home controller that does the job of filtering the data based on customer name ed from the partial view. Here is the snapshot of that.

  1. [HttpPost]  
  2. public ActionResult Filter(string custName)  
  3. {  
  4. string buttonSource = Request.Form["btnSubmit"];  
  5. if (buttonSource.Equals("Filter") && !string.IsNullOrEmpty(custName))  
  6. {  
  7. List<Customer> lstCustomers = SampleData.GetDummyCustomer().Where(x => x.Name.Equals(custName, StringComparison.InvariantCultureIgnoreCase)).ToList();  
  8. ViewBag.CustomerName = custName;  
  9. return View("Index", lstCustomers);  
  10. }  
  11. else  
  12. {  
  13. ViewBag.CustomerName = null;  
  14. return View("Index", SampleData.GetDummyCustomer());  
  15. }  

Here is the snapshot of the outcome:


You can also create a partial view as a strongly typed partial view. We'll further make modification in the code above so that it makes use of a label control to display about the searching criteria. I've added a new partial view with the name “FilterBy.cshtml” and also we made it strongly typed with string as the type. Here is the code for that.

  1. @model string  
  2. <div style="border: 2px solid silver; float: left; text-transform: capitalize;">  
  3. Filter applied on Name: " @Model "  
  4. </div> 

We'll include this partial view inside the main view, in other words Index.cshtml. Here is the piece of code that we added.

  1. @{  
  2. string[] arr = Model.Select(x => x.Name).ToArray<string>();  
  3. string filterBy = arr.Length > 1 ? "NONE" : arr[0];  
  4. }  
  5. <h2>  
  6. Customer Details</h2>  
  7. <table>  
  8. <tr>  
  9. <td>  
  10. @Html.Partial("FilterCustomer")  
  11. </td>  
  12. </tr>  
  13. <tr>  
  14. <td>  
  15. @Html.Partial("FilterBy", filterBy)  
  16. </td>  
  17. </tr>  
  18. </table> 



3. Sections

Ok now for demonstrating this let's try to create sections inside the index.cshtml file and also make a provision for displaying those sections using the _Layout.cshtml file. Inside the _Layout.cshtml file we by default have a RenderBody() method that does the work of displaying the body of the page/view on which the _Layout.cshtml is been applied. By default every _Layout.cshtml will have this method that acts as renderer to display the content of the view. Razor allows you to create multiple sections inside the _Layout.cshtml except the one that already exists. To define a new section we need to make use of the RenderSection method that does the work of rendering the view section by section. There could be multiple sections defined inside the _Layout.cshtml file as needed and some of them could be mandatory or optional. We'll do certain modifications in this _Layout.cshtml so that it displays the section as we desire. These are the changes we made in the _Layout.cshtml:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="utf-8" />  
  5. <meta name="viewport" content="width=device-width" />  
  6. <title>@ViewBag.Title</title>  
  7. @Styles.Render("~/Content/css")  
  8. @Scripts.Render("~/bundles/modernizr")  
  9. @Scripts.Render("~/bundles/jquery")  
  10. @RenderSection("scripts", required: false)  
  11. </head>  
  12. <body>  
  13. <div style="background-color: #0e0e6c; color: White;font-weight:bold; border-radius: 5px; width: 450px; text-align:center;">  
  14. Below is the header Section</div>  
  15. @RenderSection("Header")  
  16. <div style="background-color: #0e0e6c;font-weight:bold; color: White; border-radius: 5px; width: 450px;text-align:center;">  
  17. Below is the Content Section</div>  
  18. @RenderSection("Content")  
  19. <div style="background-color: #0e0e6c; color: White; border-radius: 5px; margin-top: 20px;  
  20. width: 450px;text-align:center; font-weight:bold;">  
  21. Below is the Footer Section</div>  
  22. @RenderSection("Footer")  
  23. </body>  
  24. </html> 

And these are the changes we did in the Index.cshtml file, where in accordance with the _Layout.cshtml file we defined the view in a number of sections. Since all the sections are mandatory we need to define all of them.

  1. @using DynamicView.Models  
  2. @model IEnumerable<Customer>  
  3. @{  
  4. ViewBag.Title = "Index";  
  5. }  
  6. @{  
  7. string[] arr = Model.Select(x => x.Name).ToArray<string>();  
  8. string filterBy = arr.Length > 1 ? "NONE" : arr[0];  
  9. }  
  10. @section Header  
  11. {  
  12. <h2>  
  13. Customer Details</h2>  
  14. }  
  15. @section Content  
  16. {  
  17. <table>  
  18. <tr>  
  19. <td>  
  20. @Html.Partial("FilterCustomer")  
  21. </td>  
  22. </tr>  
  23. <tr>  
  24. <td>  
  25. @Html.Partial("FilterBy", filterBy)  
  26. </td>  
  27. </tr>  
  28. </table>  
  29. <div class="CSSTableGenerator" style="width: 350px;">  
  30. <table>  
  31. <tr>  
  32. <td>  
  33. ID  
  34. </td>  
  35. <td>  
  36. Name  
  37. </td>  
  38. <td>  
  39. Address  
  40. </td>  
  41. <td>  
  42. Customer Type  
  43. </td>  
  44. </tr>  
  45. @foreach (var cust in Model)  
  46. {  
  47. <tr>  
  48. <td>  
  49. @cust.CustID  
  50. </td>  
  51. <td>  
  52. @cust.Name  
  53. </td>  
  54. <td>  
  55. @cust.Address  
  56. </td>  
  57. <td>  
  58. @* @if (cust.CustomerType == CustomerType.Regular)  
  59. {  
  60. <font color="green">@cust.CustomerType</font>  
  61. }  
  62. else if (cust.CustomerType == CustomerType.FirstTime)  
  63. {  
  64. <font color="pink">@cust.CustomerType</font>  
  65. }  
  66. else  
  67. {  
  68. <font color="gray">@cust.CustomerType</font>  
  69. }*@  
  70. @switch (cust.CustomerType)  
  71. {  
  72. case CustomerType.Regular:  
  73. <font color="green">@cust.CustomerType</font>  
  74. break;  
  75. case CustomerType.FirstTime:  
  76. <font color="#0e0e6c">@cust.CustomerType</font>  
  77. break;  
  78. default:  
  79. <font color="gray">@cust.CustomerType</font>  
  80. break;  
  81. }  
  82. </td>  
  83. </tr>  
  84. }  
  85. </table>  
  86. </div>  
  87. }  
  88. @section Footer  
  89. {  
  90. Asp.Net MVC4 Example on placing dynamic content inside Views  

The output of that is displayed below.



NOTE: A view must contain all the mandatory sections defined inside the _Layout.cshtml file. In order to create an optional section we just need to the second parameter while creating the section inside the _Layout.cshtml file like the following. We just changed the @RenderSection(“Footer”) with the following line:

  1. @RenderSection("Footer"false

The preceding line makes the footer section optional.

In order to deal with optional sections we can use the IsSectionDefined() function in the _Layout.cshtml file to check whether the user has placed code for the section or not. This can also help us to display the default value for the section if there is no section content supplied by the view. To check whetehr or not the footer content has been supplied by the view we can use the following statement

  1. @if (IsSectionDefined("footer"))  
  2. @RenderSection("Footer"false)  
  3. else  
  4. {  
  5. <div>  
  6. Asp.Net MVC4 Example on placing dynamic content inside Views  
  7. </div>  

4. HTML Helper Methods

A helper method provides a way to reuse a piece of code among multiple controls and also provides us a way to add a new functionality to the existing control helper methods. These are nothing but you extension methods in C#. There are the following various types of helper methods:

  • Built-In Helper Method
  • Internal Helper Method
  • External Helper Method/Custom Helper Method

For a built-In helper method there are various methods available that help us to perform various things. Like the following:

  1. @using (Html.BeginForm("Filter""Home", FormMethod.Post, new { id = "filterForm" }))  
  2. {  
  3. //piece of code  
  4. }  
  5.   
  6. @Html.TextBox(“txtName”,”Value”) 

And many more are there that includes some strongly typed helper methods when model binding is used, for example:

  1. @Html.TextBoxFor(model=>model.Name)  
  2.   
  3. @Html.RadioButtonFor(model=>model.Gender) 

Now let's take an example of the Internal Helper Method. We have made some changes in the Index.cshtml file; here is the code snippet for that.

  1. @using DynamicView.Models  
  2. @model IEnumerable<Customer>  
  3. @{  
  4. ViewBag.Title = "Index";  
  5. }  
  6. @{  
  7. string[] arr = Model.Select(x => x.Name).ToArray<string>();  
  8. string filterBy = arr.Length > 1 ? "ALL" : arr[0];  
  9. }  
  10. @helper RenderCustomerType(CustomerType type)  
  11. {  
  12. switch (type)  
  13. {  
  14. case CustomerType.Regular:  
  15. <font color="green">@type.ToString()</font>  
  16. break;  
  17. case CustomerType.FirstTime:  
  18. <font color="#0e0e6c">@type.ToString()</font>  
  19. break;  
  20. default:  
  21. <font color="gray">@type.ToString()</font>  
  22. break;  
  23. }  
  24. }  
  25. @section Header  
  26. {  
  27. <h2>  
  28. Customer Details</h2>  
  29. }  
  30. @section Content  
  31. {  
  32. <table>  
  33. <tr>  
  34. <td>  
  35. @Html.Partial("FilterCustomer")  
  36. </td>  
  37. </tr>  
  38. <tr>  
  39. <td>  
  40. @Html.Partial("FilterBy", filterBy)  
  41. </td>  
  42. </tr>  
  43. </table>  
  44. <div class="CSSTableGenerator" style="width: 350px;">  
  45. <table>  
  46. <tr>  
  47. <td>  
  48. ID  
  49. </td>  
  50. <td>  
  51. Name  
  52. </td>  
  53. <td>  
  54. Address  
  55. </td>  
  56. <td>  
  57. Customer Type  
  58. </td>  
  59. </tr>  
  60. @foreach (var cust in Model)  
  61. {  
  62. <tr>  
  63. <td>  
  64. @cust.CustID  
  65. </td>  
  66. <td>  
  67. @cust.Name  
  68. </td>  
  69. <td>  
  70. @cust.Address  
  71. </td>  
  72. <td>  
  73. @RenderCustomerType(cust.CustomerType)  
  74. </td>  
  75. </tr>  
  76. }  
  77. </table>  
  78. </div>  
  79. }  
  80. @section Footer  
  81. {  
  82. Footer Section defined inside the Index.cshtml file  

As you can see we used an inline helper function instead of mixing the code inside the design. And we can easily call the helper function using the normal razor syntax. The output remains the same. The problem with the inline helper method is that they can only be used within that specific view itself. In order to make them reusable we need to use a C# extension function, in other words an external helper function. We'll add a new C# file inside the “Infrastructure” folder with the name “CustomHelper.cs”. Here is the code snippet for that:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using DynamicView.Models;  
  7.   
  8. namespace DynamicView.Infrastructure  
  9. {  
  10. public static class CustomHelper  
  11. {  
  12. public static MvcHtmlString RenderCustomerType(this HtmlHelper helper, CustomerType type)  
  13. {  
  14. TagBuilder builder = new TagBuilder("font");  
  15. switch (type)  
  16. {  
  17. case CustomerType.Regular:  
  18. builder.Attributes.Add("Color""green");  
  19. break;  
  20. case CustomerType.FirstTime:  
  21. builder.Attributes.Add("color""#0e0e6c");  
  22. break;  
  23. default:  
  24. builder.Attributes.Add("color""gray");  
  25. break;  
  26. }  
  27. builder.SetInnerText(type.ToString());  
  28. return new MvcHtmlString(builder.ToString());  
  29. }  
  30. }  

Here is the change made in the index.cshtml file:

  1. @using DynamicView.Models  
  2. @using DynamicView.Infrastructure  
  3. @model IEnumerable<Customer>  
  4. @{  
  5. ViewBag.Title = "Index";  
  6. }  
  7. @{  
  8. string[] arr = Model.Select(x => x.Name).ToArray<string>();  
  9. string filterBy = arr.Length > 1 ? "All" : arr[0];  
  10. }  
  11. @*@helper RenderCustomerType(CustomerType type)  
  12. {  
  13. switch (type)  
  14. {  
  15. case CustomerType.Regular:  
  16. <font color="green">@type.ToString()</font>  
  17. break;  
  18. case CustomerType.FirstTime:  
  19. <font color="#0e0e6c">@type.ToString()</font>  
  20. break;  
  21. default:  
  22. <font color="gray">@type.ToString()</font>  
  23. break;  
  24. }  
  25. }*@  
  26. @section Header  
  27. {  
  28. <h2>  
  29. Customer Details</h2>  
  30. }  
  31. @section Content  
  32. {  
  33. <table>  
  34. <tr>  
  35. <td>  
  36. @Html.Partial("FilterCustomer")  
  37. </td>  
  38. </tr>  
  39. <tr>  
  40. <td>  
  41. @Html.Partial("FilterBy", filterBy)  
  42. </td>  
  43. </tr>  
  44. </table>  
  45. <div class="CSSTableGenerator" style="width: 350px;">  
  46. <table>  
  47. <tr>  
  48. <td>  
  49. ID  
  50. </td>  
  51. <td>  
  52. Name  
  53. </td>  
  54. <td>  
  55. Address  
  56. </td>  
  57. <td>  
  58. Customer Type  
  59. </td>  
  60. </tr>  
  61. @foreach (var cust in Model)  
  62. {  
  63. <tr>  
  64. <td>  
  65. @cust.CustID  
  66. </td>  
  67. <td>  
  68. @cust.Name  
  69. </td>  
  70. <td>  
  71. @cust.Address  
  72. </td>  
  73. <td>  
  74. @Html.RenderCustomerType(cust.CustomerType)  
  75. </td>  
  76. </tr>  
  77. }  
  78. </table>  
  79. </div>  
  80. }  
  81. @section Footer  
  82. {  
  83. Footer Section defined inside the Index.cshtml file  

5. Child Actions

These are action methods that we can invoke from the view. To invoke an action as a child action we need to set the attribute [ChildActionOnly] above the action method. The child action can only invoke partial views since these are called from within a view. To demonstrate this we'll try to create a partial view and a child action that will display the number of records being fetched from the database before or after filtering. For doing this I’m adding a new strongly typed partial view to the shared folder with the name “FetchCount.cshtml”. Here is the code snippet for that:

  1. @model int  
  2. <div style="border: 1px solid silver; float: left; text-transform: capitalize; width: 180px;  
  3. border-radius: 5px; text-align: left; float: left; margin-left:0px;">  
  4. Records Fetched: <b>@Model</b>  
  5. </div> 

Here is the ChildAction Code in HomeController:

  1. public PartialViewResult FetchCount(int count)  
  2. {  
  3. return PartialView("FetchCount", count);  

Here is our latest index.cshtml file where we’ve made the final changes:

  1. @using DynamicView.Models  
  2. @using DynamicView.Infrastructure  
  3. @model IEnumerable<Customer>  
  4. @{  
  5. ViewBag.Title = "Index";  
  6. }  
  7. @{  
  8. string[] arr = Model.Select(x => x.Name).ToArray<string>();  
  9. string filterBy = arr.Length > 1 ? "NONE" : arr[0];  
  10. }  
  11. @*@helper RenderCustomerType(CustomerType type)  
  12. {  
  13. switch (type)  
  14. {  
  15. case CustomerType.Regular:  
  16. <font color="green">@type.ToString()</font>  
  17. break;  
  18. case CustomerType.FirstTime:  
  19. <font color="#0e0e6c">@type.ToString()</font>  
  20. break;  
  21. default:  
  22. <font color="gray">@type.ToString()</font>  
  23. break;  
  24. }  
  25. }*@  
  26. @section Header  
  27. {  
  28. <h2>  
  29. Customer Details</h2>  
  30. }  
  31. @section Content  
  32. {  
  33. <table style="width: 500px;">  
  34. <tbody>  
  35. <tr>  
  36. <td>  
  37. @Html.Partial("FilterCustomer")  
  38. </td>  
  39. </tr>  
  40. <tr>  
  41. <td style="float: left; display: inline-block;">  
  42. @Html.Action("FetchCount"new { count = Model.Count() })  
  43. @Html.Partial("FilterBy", filterBy)  
  44. </td>  
  45. </tr>  
  46. </tbody>  
  47. </table>  
  48. <div class="CSSTableGenerator" style="width: 350px;">  
  49. <table>  
  50. <tr>  
  51. <td>  
  52. ID  
  53. </td>  
  54. <td>  
  55. Name  
  56. </td>  
  57. <td>  
  58. Address  
  59. </td>  
  60. <td>  
  61. Customer Type  
  62. </td>  
  63. </tr>  
  64. @foreach (var cust in Model)  
  65. {  
  66. <tr>  
  67. <td>  
  68. @cust.CustID  
  69. </td>  
  70. <td>  
  71. @cust.Name  
  72. </td>  
  73. <td>  
  74. @cust.Address  
  75. </td>  
  76. <td>  
  77. @Html.RenderCustomerType(cust.CustomerType)  
  78. </td>  
  79. </tr>  
  80. }  
  81. </table>  
  82. </div>  
  83. }  
  84. @section Footer  
  85. {  
  86. Footer Section defined inside the Index.cshtml file  

Here is the output for that where all things are working:



Now filter the records and you’ll see that the count has changed.


 

Up Next
    Ebook Download
    View all
    Learn
    View all