Tuesday, 13 May 2014

MVC Tips : Writing Custom Razor helper class

Click Here to Download CustomRazorHelperClass.zip

It is very easy to write custom razor helper class. After creating custom razor helper class, we can use these classes anywhere in MVC Application.

Here is step by step explanation of creation of razor helper class.

STEP 1 :
First create MVC web application if you do not have MVC Web Application

STEP 2 :
Now Add new "App_Code" folder. In this folder add MVC Razor View page (MVC 4 View Page (Razor)).

To do this, you need to do right click on 'App_Code' folder and click on "Add New Item" menu. It will display dialog box to add new item. After that add 'MVC 4 View Page (Razor)' Page. Give it named like 'CustomRazorHelper.cshtml'.

Now we add one method name 'ToTitleCase', this method makes first character upper case of given statement and make rest of the characters lower case.

Below code is for 'ToTitleCase' method :
@helper ToTitleCase(string input)
    if (input.Length >0) {
        @(input.First().ToString().ToUpper() + String.Join("", input.Skip(1)).ToLower());

STEP 3 :
Now add one controller name 'HomeController' and add 'Index' view for that.

Below code is for 'HomeController' :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CustomRazorHelperClass.Controllers
    public class HomeController : Controller
        // GET: /Home/

        public ActionResult Index()
            return View();


Below code is for 'Index' view of 'HomeController' : 
    ViewBag.Title = "Index";
<h2>@CustomRazorHelper.ToTitleCase("hello TesTING")</h2>

You can see in output that our given string is displayed in title case format.

Output : 

Below are the books that you would like :

1 comment:

  1. check the Razor syntax and more stuff here..