Home/MVC/Reusing @helpers Method across multiple views in mvc

Reusing @helpers Method across multiple views in mvc

Here we going to discuss about how to make the @helper method can be reusable across all multiple views in our project. We can achieve this by placing .cshtml in the App_Code folder to make visible to access across the application.

.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>

READ  Handling Unknown Actions in ASP.NET MVC

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.

One Comment

  1. Ann December 22, 2015 at 4:00 pm

    Great, it’s working ok 🙂 Thanks

Leave A Comment