Reusing @helpers Method across multiple views in mvc

Note : Hi guys please visit new website for future posts http://www.dotnet-helpers.com. Thanks for support

 

Reusing @helpers Method across multiple views :

Here we discuss how to make the @helper method enable reusable across all of the view templates in our project.

We can achieve this by placing .cshtml in the App_Code folder to make visible to access

 

.cshtml : (indside  App_Code)

<html>
<body>
@helper CretingMultipleRow(int loopvalue)
{
<table>
@for (int loop_index = 0; loop_index < loopvalue; loop_index++)
{
<tr id=@loopvalue>      <td>Calling helper Method : @loopvalue</td></tr>
}
</table>
}
</body>
</html>

 

In App_Code

@helpermethod1

Calling Method from the view

<html>
<body>
@HelperReusableMethod.CretingMultipleRow(5)
</body>
</html>

 

Explanation: @HelperReusableMethod.CretingMultipleRow(5)

  • @HelperReusableMethod : Name of the .cshtml file inside the App_Code
  • CretingMultipleRow(5) : Name of the method inside the HelperReusableMethod view

 

Output :

 @helpermethod

Razor’s @helper syntax provides a simple way to encapsulate/bind rendering functionality into helper methods , you can re-use within individual view , or across all view within a project.

Advertisements