[英]Role is null at Post request for ASP.NET Core Razor Pages
我有這個 Razor 頁面,其中顯示了一個文本框和一個按鈕。 單擊后,它將在表中創建/插入角色。 問題是當我在OnPostAsync
方法中放置斷點時, role
參數為 null。
這是我的前端代碼:
@page
@model CreateModel
@{
ViewData["Title"] = "Create";
}
<h1>Create Role</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Name"></label>
<input asp-for="Input.Name" class="form-control" />
<span asp-validation-for="Input.Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
這是我的代碼隱藏:
public class CreateModel : PageModel
{
private readonly RoleManager<IdentityRole> _roleManager;
public CreateModel(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
[BindProperty]
public IdentityRole Name { get; set; }
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
[Display(Name = "Role Name")]
public IdentityRole Name { get; set; }
//public string Name { get; set; }
}
public void OnGet(string returnUrl = null)
{
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(IdentityRole role) {
await _roleManager.CreateAsync(role);
return Page();
}
}
問題可能來自IdentityRole
的返回類型,在客戶端,您的瀏覽器不知道如何將變量類型轉換為IdentityRole
。 一些流行的類型是: string
、 int
、 List<T>
...
因此,在這種情況下,我建議改用字符串。
public InputModel Input { get; set; }
public class InputModel
{
public string Name { get; set; }
}
public async Task<IActionResult> OnPostAsync() {
await _roleManager.CreateAsync(new IdentityRole { Name = Input.Name });
return Page();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.