我有一个带有Angular 7材质设计客户端的ASP.NET Web API。我想为当前用户分配一个角色, 我正在尝试向其分配角色的用户。我已经运行了.Net部分,但我想不出如何在角度方面实现它。我不确定我是否正确执行了select下拉列表。 在我的console.log()中,该角色显示为“未定义”。任何帮助表示赞赏。
以下是当前代码。
ASP.NET Web API
[HttpPost]
public async Task<IActionResult> Role(Roles role)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var assignRole = await _contextFile.AddRoles(role.Email, role.UserRoles);
}
catch (Exception ex)
{
throw ex;
}
return Ok();
}
Angular 7
服务
userRole(email: string, role: string){
return this.http.post(this.Url + {email, role});
}
populateDropdownRoles(){
return this.http.get(this.roleUrl);
}
.ts文件
assignRole() {
this.roleService.userRole(this.user.email, this.role);
}
dropdownRole() {
this.roleService.populateDropdownRoles();
}
.html文件
<form (ngSubmit)="assignRole()">
<mat-form-field>
<input
matInput
placeholder="Email"
name="email"
value="{{ user.email}}"
/>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Role">
<mat-option *ngFor="let role of roles" name ="rolename" [(ngModel)]="role.rolename" value="{{role.rolename}}">
{{role.rolename}}
</mat-option>
</mat-select>
</mat-form-field>
<button
mat-raised-button
type="submit"
>
Assign
</button>
</form>
答案 0 :(得分:1)
我只是很快地将其模拟了,这是有效的。您可能需要修改某些变量名。
[(ngModel)]
和name
移至<mat-select>
元素。[(ngModel)]
的变量。assignRole()
方法打印出选定的值。注意:这是假设您已成功从API接收回角色值。我在组件类中添加了一个模拟角色数组。
@Component({
selector: 'app-roles-form',
templateUrl: './roles-form.component.html',
styleUrls: ['./roles-form.component.css']
})
export class RolesFormComponent implements OnInit {
public roles = [{ rolename: 'user' }, { rolename: 'admin' }];
public selectedRole: any;
constructor() { }
ngOnInit() {
}
assignRole() {
console.log('selectedRole: ', this.selectedRole);
}
}
<form (ngSubmit)="assignRole()">
<mat-form-field>
<mat-select placeholder="Role" [(ngModel)]="selectedRole" name="selectedRole">
<mat-option *ngFor="let role of roles" value="{{role.rolename}}">
{{role.rolename}}
</mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button type="submit">
Assign
</button>
</form>
答案 1 :(得分:0)
我注意到了一些事情:控制器中模型的名称是角色,并且根据服务方法中接收的参数是一个字符串,因此您应该使用[(ngModel)] =“ role”认为您应该将其放在mat-select标记而不是mat-option处。因此,您的html应该看起来像这样。
<mat-form-field>
<mat-select [(ngModel)]="role" name ="role" placeholder="Role">
<mat-option *ngFor="let role of roles" value="{{role.rolename}}">
{{role.rolename}}
</mat-option>
</mat-select>
</mat-form-field>
PS:建议您将模型名称更改为roleName。像this.roleName和[(ngModel)] =“ roleName” name =“ roleName”这样,您就不会感到困惑。 You could check the example here
答案 2 :(得分:0)
您遇到了ngModel
错误,ngModel
位于控件而非选项上。
<mat-select [(ngModel)]="role" name ="rolename" placeholder="Role">
<mat-option *ngFor="let role of roles" [value]="role.rolename">
{{role.rolename}}
</mat-option>
</mat-select>
此后,您需要检查.Net
部分Role
的结构,因为如果我的记忆没有失败,那么UserRoles
属性将列出所选角色,如果正确,那么您需要发送一组角色,而不仅仅是一个角色。