Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC Reusable Components

0.00/5 (No votes)
19 Jul 2016 1  
Demonstration of Reusable components in MVC

Introduction

In a web application, there can be multiple locations which display same functionality or with some nuances. Writing the same code again and again is not an ideal solution. Moreover, it will be a maintenance nightmare if changes are to be done in the existing functionality. Therefore, it is a best practice to stick to reusable components when it comes to working on a MVC web application.

MVC very efficiently supports reusability of components via Partial Views, Custom Html Helpers, Child Actions, @section and @helper.

Background

I have been working on a web application which has different workflows to be followed in different scenarios, though most of the components are common but are shown at different stages in workflows. Therefore, it has become far more important to implement reusable components.

Using the Code

The user should have a basic understanding of MVC project structure and C# extension methods beforehand.

Partial View

Add a view as partial view to the shared folder of Views section, naming convention for it is _<viewname>.

Partial view can be called in a normal view via these two ways:

Html.RenderPartial ("_HeadingPartial")

Or

@Html.Partial ("_HeadingPartial")

Custom HTML Helper

Custom HTML Helpers can be added in a couple of ways:

1. Custom HtmlHelper using Extension Method

Adding an extension method to an existing HtmlHelper class can come in handy for reusability of code. Implementation of HtmlHelper Extension method will be done firstly by creating an extension method.

namespace MVC_Reusability.CustomHelper
{
    public static class HtmlHelperExt
    {
        public static MvcHtmlString CustomHelperMethod(this HtmlHelper html)
        {
            var ul = new TagBuilder("ul");
            ul.InnerHtml += Environment.NewLine;
            var li1 = new TagBuilder("li");
            li1.SetInnerText("List Index 1");
            var li2 = new TagBuilder("li");
            li2.SetInnerText("List Index 2");

            ul.InnerHtml += string.Format
            (" {0}{1}", li1.ToString(), Environment.NewLine);
            ul.InnerHtml += string.Format
            (" {0}{1}", li2.ToString(), Environment.NewLine);

            return MvcHtmlString.Create(ul.ToString());
        }   
    }
}

Secondly, by adding its namespace to view where it needs to be called.

@using MVC_Reusability.CustomHelper or if you want it to be accessible to whole application, add to namespace to web.config.

<add namespace=" MVC_Reusability.CustomHelper " />

Finally, call the HtmlHelper extension method at the desired location.

@Html.CustomHelperMethod()

2. Custom HtmlHelper using Static Method

Another approach for creating custom HtmlHelpers is by using static methods, which can be reused at various locations in an application. To implement it firstly static method is to be created which renders either string or MVCHtmlString.

namespace MVC_Reusability.CustomHelper
{
    public static class HtmlHelperExt
    {
        public static MvcHtmlString CustomStaticHelperMethod()
        {
            var span = new TagBuilder("span");
            span.InnerHtml = "This span is from custom static helper method";
            return MvcHtmlString.Create(span.ToString());
        }
   }
}

Secondly, by adding its namespace to view where it needs to be called.

@namespace MVC_Reusability.CustomHelper

Finally, call the HtmlHelper static method at the desired location.

@HtmlHelperExt.CustomStaticHelperMethod()

Child Action Methods

Child Actions are designed to be called from within views which gives it an advantage to be used as a reusable component inside views. To implement it, a controller method is to be created with attribute ChildActionOnly.

[ChildActionOnly]
public ActionResult FetchChildAction()
{
    return View("ChildActionView");
}

The child action method can be invoked from any view via the following two methods:

@Html.Action("FetchChildAction")

Or

@{ Html.RenderAction ("FetchChildAction"); }

@section

@section works in tandem with layout. The website should have a consistent look and feel throughout, i.e., header, footer, etc. which can be setup in layout page but there would be some sections in layout which do need customization depending upon the page. Such customization can be achieved from @section.

The layout page will have methods declared to render various sections:

<div class="container body-content">
    @RenderBody()
    @RenderSection("featuredSection", required: false)
    <hr />
    <footer>
        <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
</div>

The views for controller methods will have specific sections defined which will be used by the render methods inside layout file.

@section featuredSection
{ <h3>This text falls in from section called featuredSection</h3> }

@helper

@helper allows you to create a method that can encapsulate output functionality within your view templates.

@helper DisplayWishMessage()
{
    if (DateTime.Now.ToString("tt") == "AM")
    {
         <h3>Have a good Day!!</h3>

The method can be called directly within view directly wherever required.

<div>
   @DisplayWishMessage()
</div>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here