Friday, 31 January 2020

ASP.NET MVC 3 and the @helper syntax within Razor

When you make a website then sometimes you need to make a reusable HTML component, for example, you want to show testimonial on the various page. For doing this you need to copy-paste testimonial HTML on pages where it is required. The problem arises when any modification is done on Testimonial, You will have to update testimonial manually on every page which is time taking and prone to error.




You can make a reusable HTML component in ASP.Net MVC platform using helper class . We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project.  For example, below I created a “ScottGu.cshtml” file within the \App_Code folder, and defined two separate helper methods within the file (you can have any number of helper methods within each file)


Pagelib.cshtml code


@helper demo() {

<h1>Funaction called</h1>
}

@helper PrintName(string name) {
    <h2 style="color:blue">Hello @name</h2>
    }


Calling on view


@PageLib.demo()
@PageLib.PrintName("Raj")

No comments:

Post a Comment