【发布时间】:2020-04-26 09:25:37
【问题描述】:
我是 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;
}
}
}
【问题讨论】:
标签: .net blazor blazor-server-side