我试图为管理员创建一个Razor页面,通过复选框选择用户的角色来添加用户。但我没有得到想要的结果。
Pagemodel:
[BindProperty(SupportsGet = true)]
public InputModel Input { get; set; }
public class InputModel
{
public string Email {get; set;}
...
public list<rol> rollen {get;set;}
}
public class rol
{
public string name {get;set}
public bool selected {get;set;}
}
在OnGet():
Input.rollen = (from rol in _roleManager.Roles
select new rol
{
name = rol.Name,
selected = false
}).ToList();
在页面中。
@foreach (var rol in Model.Input.rollen.OrderBy(x=>x.name))
{
<div class="form-check">
<input class="form-check-input" type="checkbox" id="@rol.name" name="@rol.name">
<label class="form-check-label" for="@rol.name">
@rol.name
</label>
</div>
}
视觉上它给出了正确的结果。但当然在发布表单时,它与模型不匹配。请问正确的方法是什么?我可以一个一个手动添加复选框,但这不是真正的方法。
我使用thins页面找到了答案。https:/www.learnrazorpages.comrazor-pagesformscheckboxes.
我补充道
[BindProperty]
public InputModel Input { get; set; }
[BindProperty]
public List<string> roles { get; set; }
Onget:
public void OnGet()
{
var rollen = _roleManager.Roles.OrderBy(x => x.Name).Select(x => x.Name).ToList();
ViewData["roles"] = roles;
}
在页面上。
<div class="form-row">
<label class="col-md-3 col-form-label">Rollen</label>
<div class="form-group col-md-9">
@foreach(var role in ViewData["roles"] as List<string>)
{
<div class="form-check">
<input class="form-check-input" type="checkbox" name="roles" value="@role">
<label class="form-check-label">
@role
</label>
</div>
}
</div>
</div>
在Post上,你会得到一个列表,其中包含了所有的。检查 值。重要的是,所有的复选框都有相同的名称属性。
我之前找到了那个页面,但我就是没有让它工作。但那是因为我将List添加为InputModel的一部分。我不得不把它作为Bindproperty单独添加。