Custom helper method in ASP.NET MVC

How to create & call an inline custom helper method in Razor markup?

Sometimes, we need to create a custom helper method in the Razor to avoid the duplication of the code. To do that we can use @helper markup followed by the name of the method and parameters if any. 
@helper AddSalutation(string name)
 {  
   <b>Mr. @name</b>
 }
To call this helper method, we can call it as if it is any other method defined in Razor server side block.
<li>Inline Helper Method Output: @AddSalutation("Sheo Narayan")</li> 

The output of AddSalutation method will be "Mr. Sheo Narayan".

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...