c# - 如何从 IList 中获取 Id模型内?
问题描述
有没有一种简单的方法可以从另一个模型中的 IList 获取 id?最好用剃须刀?我想在 IList 角色中获取 RoleId。
public class EditUserViewModel
{
public EditUserViewModel()
{
Claims = new List<string>(); Roles = new List<string>();
}
public string Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public string City { get; set; }
public List<string> Claims { get; set; }
public IList<string> Roles { get; set; }
}
}
public class ManageUserRoleViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool IsSelected { get; set; }
//Viewbag is used to store UserId
}
public class UserRoleViewModel
{
public string UserId { get; set; }
public string UserName { get; set; }
public bool IsSelected { get; set; }
//Viewbag is used to store UserId
}
<table class="table table-hover table-md ">
<thead>
<tr>
<td class="text-left TableHead">Role</td>
<td class="text-right TableHead">Delete</td>
</tr>
</thead>
@*--Table Body For Each to pull DB records--*@
<tbody>
@foreach (var role in Model.Roles)
{
<tr>
<td>@role</td>
<td>
<button class="sqButton btnRed float-right zIndex" id="Delete" title="Delete" data-toggle="ajax-modal" data-target="#deleteRoleUser" data-url="@Url.Action("Delete", "Administration", new {Id = Model.Id , Type = "roleUser"})">
<i class="glyphicon glyphicon-remove"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
我正在尝试将角色 ID 与@Url.Action 中的其他参数一起传递,但我似乎无法弄清楚将其拉入的秘密,因此我可以将其传递给后端控制器。
解决方案
问题是
public IList<string> Roles { get; set; }
仅包含字符串,因此无需查找 ID。您必须将此行更改为
public IList<ManageUserRoleViewModel> Roles { get; set; }
这样,您就有了一个包含 ID 的对象列表。然后,在您看来,您可以这样做:
@Model.Roles.FirstOrDefault(x => x.RoleId == YOUR_UNIQUE_ID)
这将为您提供一个对象来执行进一步的逻辑。
推荐阅读
- json - 使用 Spark 按行和列扩展 JSON 字符串
- javascript - 将原型传递给 Object.Create()
- typescript - 扩展现有验证器并仅设置一些选项
- chart.js - 如何在chartJS中将一个值与另一个值进行比较
- html - 带有表格布局的表格:在 Firefox 中固定 100% 高度
- c# - 在这种情况下如何使查找字段工作而不在数据库中定义外键?
- python - 如何使用python子进程输入管道
- flutter - Flutter:文本仅在点击按钮两次后更新
- amazon-web-services - AWS 中的 AMI 到底是什么?
- r - R中的内存问题“错误:无法分配大小为344 kb的向量”