Option 1 - DI
1 - Create the service class with the relevant functionality
public class FullNameService
{
public string GetFullName(string first, string last)
{
return $"{first} {last}";
}
}
2- Register the service in startup
services.AddTransient<FullNameService>();
3- Inject it to the razor page
public class IndexModel : PageModel
{
private readonly FullNameService _service;
public IndexModel(FullNameService service)
{
_service = service;
}
public string OnGet(string name, string lastName)
{
return _service.GetFullName(name, lastName);
}
}
1- Create a base page model with the function
public class BasePageModel : PageModel
{
public string GetFullName(string first, string lastName)
{
return $"{first} {lastName}";
}
}
2- Derive other pages from the base model
public class IndexModel : BasePageModel
{
public string OnGet(string first, string lastName)
{
return GetFullName(first, lastName);
}
}
1- Use a static function that can be accessed from all pages
public static class FullNameBuilder
{
public static string GetFullName(string first, string lastName)
{
return $"{first} {lastName}";
}
}
2- Call the static function from the razor page
public class IndexModel : PageModel
{
public string OnGet(string first, string lastName)
{
return FullNameBuilder.GetFullName(first, lastName);
}
}
1- Create an extension method for a specific type of objects (e.g. string)
public static class FullNameExtensions
{
public static string GetFullName(this string first, string lastName)
{
return $"{first} {lastName}";
}
}
2- Call the extension from razor page
public class IndexModel : PageModel
{
public string OnGet(string first, string lastName)
{
return first.GetFullName(lastName);
}
}