[英]Role is null at Post request for ASP.NET Core Razor Pages
I have this Razor Pages which show a textbox and a button.我有这个 Razor 页面,其中显示了一个文本框和一个按钮。 Upon clicked, it will create/insert a Role into the table.
单击后,它将在表中创建/插入角色。 Problem is when I put a breakpoint at the
OnPostAsync
method, role
parameter is null.问题是当我在
OnPostAsync
方法中放置断点时, role
参数为 null。
This is my front-end code:这是我的前端代码:
@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>
This is my code-behind:这是我的代码隐藏:
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();
}
}
The problem may come from the returned type of IdentityRole
, in the client, your browser doesn't know how to convert a variable type to IdentityRole
.问题可能来自
IdentityRole
的返回类型,在客户端,您的浏览器不知道如何将变量类型转换为IdentityRole
。 Some popular types are: string
, int
, List<T>
...一些流行的类型是:
string
、 int
、 List<T>
...
So, in this case, I suggest to use a string instead.因此,在这种情况下,我建议改用字符串。
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.