【发布时间】:2018-10-25 18:56:18
【问题描述】:
我只是想为我的身份数据库创建一个编辑页面。我正在使用 Razor Pages,而且我是新手。我为 MVC 找到了一些解决方案,但由于使用了视图和其他东西(如控制器),它们并没有真正为我工作。我有一个主页 Index.cshtml,我可以从如下图的列表中选择用户
然后通过单击提交按钮将其删除。
我这样处理删除:
CSHTML 文件:
<button type="submit" class="btn btn-sm btn-danger" asp-route-id="@user.Id" asp-page-handler="Del">Del</button>
<button type="submit" class="btn btn-sm btn-primary" asp-route-id="@user.Id" asp-page-handler="Change">Change</button>
CSHTML.CS 文件:
public ApplicationUser ApUser { get; set; }
public async Task<ActionResult> OnPostDel(string id)
{
ApUsers = _userManager.Users.ToList();
ApUser = await _userManager.FindByIdAsync(id);
if (ApUser != null)
{
IdentityResult result = await _userManager.DeleteAsync(ApUser);
}
//return RedirectToAction("UserChange/Index");
return RedirectToPage("Index");
}
它对我来说很好用,但我也需要编辑。所以我在 Index.cshtml.cs 中的 Edit POST 方法看起来像:
public async Task<ActionResult> OnPostChange(string id)
{
ApUsers = _userManager.Users.ToList();
ApUser = await _userManager.FindByIdAsync(id);
if (ApUser == null)
{
return NotFound();
}
else return RedirectToPage("Edit");
}
而我的 Edit.cshtml.cs 看起来像这样:
<form asp-action="Edit" asp-controller="Users">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<input type="hidden" asp-for="Id" />
</div>
<div class="form-group">
<label asp-for="Email" class="control-label">Email</label>
<input type="text" asp-for="Email" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Score" class="control-label">Score</label>
<input type="number" asp-for="Score" class="form-control" />
</div>
...
<div class="form-group">
<input type="submit" asp-page-handler="Edit" value="Save" class="btn btn-default" />
</div>
</form>
还有Edit.cshtml.cs:
public async Task<IActionResult> OnPostEdit(string id)
{
if (ModelState.IsValid)
{
ApUser = await _userManager.FindByIdAsync(id);
if (ApUser != null)
{
ApUser.Email = Email;
ApUser.UserName = Email;
ApUser.Score = Score;
ApUser.Position = Position;
ApUser.Sequence = Sequence;
var result = await _userManager.UpdateAsync(ApUser);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
}
return RedirectToAction("Index");
}
当然,它不起作用。我只是想将一些 MVC 示例重新制作为 Razor Pages。也许您对此有更好的解决方案,但我真的卡在这里。
【问题讨论】:
-
当然不行这是什么意思?错误信息?什么浏览器调试控制台说的?
-
“当然不行”并不是一个很好的问题描述。我在这里看不到一个明确的问题。你的代码有什么问题?它在做什么与您的期望不同?有错误信息吗?哪些错误消息?
-
对不起,真正的问题是“如何让它工作?”,因为我不知道如何从 Index.cshtml.cs OnPostChange 方法发送 ID 参数,应该打开编辑.cshtml 页面,到 Edit.cshtml.cs 方法,如 OnPostEdit
-
尝试将
asp-page="Edit"添加到您的编辑按钮?详情请见ASP.NET Core Demystified - Razor Pages。 -
您的
Edit页面需要一个GET 路由。您正在那里重定向,因此浏览器将使用 GET 请求访问它。在那里,您需要显示一个表单,然后通过 POST 提交,您可以在其中更新值。
标签: c# asp.net-core asp.net-core-mvc asp.net-core-identity razor-pages