Hi @badcat ,
I want to combine all these two code snippet and call TranslateText function in any html part like TranslateText(@默 .Description)
You can create a service which contains the TranslateText method, then, injects the service in the view page and calling the TranslateText method.
Please refer the following steps:
Create a IViewTextFormat service with the following code (you can replace the TranslateText method to yours):
public interface IViewTextFormat
{
string TranslateText(string input);
}
public class ViewTextFormat : IViewTextFormat
{
public string TranslateText(string input)
{
return input.ToUpper();
}
}
Register the IViewTextFormat service in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IViewTextFormat, ViewTextFormat>();
Then, in the View page, injects the service:
@model List<Core3_1MVC.Models.Student>
@using Core3_1MVC.Services
@inject IViewTextFormat TextFormat
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4"> @TextFormat.TranslateText("Welcome")</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<table class="table table-hover">
<thead>
<tr><td>Name</td><td>EnrollmentDate</td></tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr><td>@TextFormat.TranslateText(item.FirstMidName)</td><td>@item.EnrollmentDate</td></tr>
}
</tbody>
</table>
The result as below:
If you want to use the service in the controller method, you can also inject the service in the controller and call the TranslateText method, refer Dependency injection in ASP.NET Core.
Besides, ASP.NET Core provides services and middleware for localizing into different languages and cultures. You can also try to use it: Globalization and localization in ASP.NET Core.
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion