我是 Blazor 的新手,我找不到关于此的直接答案/文章。
我有一个从数据库表生成的表就好了;但是,我必须添加:services.AddSingleton<ListUserMaint>();
在我的 Startup.cs 文件中。
我已经看到其他人在哪里使用 api 路由,例如:/api/ListUserMaint,但是有没有其他方法可以直接调用控制器?我正在尝试将我的控制器分开,我不想每次有新文件时都必须添加services.AddSingleton<Controller>();
。
元件:
@page "/usermaint"
@using Rogue.Controllers
@using Rogue.Models.ViewModels
@inject ListUserMaint ListUsers
@if (users == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table table-hover table-md">
<thead>
<tr>
<th class="text-left tableHead d-none" id="userId">Id</th>
<th class="text-left tableHead">CompanyName</th>
<th class="text-left tableHead">User Name</th>
<th class="text-left tableHead">First Name</th>
<th class="text-left tableHead">Last Name</th>
<th class="text-left tableHead">Title</th>
<th class="text-left tableHead">City</th>
<th class="text-left tableHead">State</th>
<th class="text-left tableHead text-right">Remove</th>
</tr>
</thead>
<tbody>
@foreach (var u in users)
{
<tr>
<td>@u.Id</td>
<td>@u.CompanyName</td>
<td>@u.UserName</td>
<td>@u.FirstName</td>
<td>@u.LastName</td>
<td>@u.Title</td>
<td>@u.City</td>
<td>@u.State</td>
<td>
<button class="sqButton btnRed float-right">
<i class="glyphicon glyphicon-remove"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
}
@code {
private IEnumerable<ListUsersViewModel.User> users;
protected override async Task OnInitializedAsync()
{
users = await ListUsers.UserMaint();
}
}
控制器:
namespace Rogue.Controllers
{
public class ListUserMaint : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private ICompanyRepository companyRepository;
//constructor
public ListUserMaint(UserManager<ApplicationUser> userManager, ICompanyRepository companyRepository)
{
this.userManager = userManager;
this.companyRepository = companyRepository;
}
[HttpGet]
public async Task <IEnumerable<ListUsersViewModel.User>> UserMaint()
{
//Get users from ApplicationUser
var users = await userManager.Users.ToListAsync();
//Create a new model for the List View (It has been extended to include CompanyName
var model = new ListUsersViewModel();
foreach (var u in users)
{
//Store this information into the List View Model and get the Company Name in the process
var userinfo = new ListUsersViewModel.User
{
UserName = u.UserName,
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
Title = u.Title,
Email = u.Email,
CompanyId = u.CompanyId,
//CompanyName = u.Company.CompanyName, //Extended via foreign key
City = u.City,
State = u.State
};
model.Users.Add(userinfo);
};
return model.Users;
}
}
}
如果使用控制器进行 CRUD 操作,则不必将其注入 DI 管道中。您应该使用 HttpClient 调用终端节点,并解析您的 json 结果。仅当需要直接从组件使用类/服务时,才需要注入类/服务。
一个好的方法是将所有控制器保留在另一个项目中,服务器托管,这样您就不会发送所有代码以与 webassebly 编译代码中的数据库进行交互