我正在使用 Microsoft Identity 使用 ASP.NET MVC 構建一個基本的博客站點。我想允許帖子的作者擁有洗掉權限,而其他人不應該。我想要做的是ViewData["isAuthor"]在控制器中操縱一個變數,并根據它們是否通過檢查傳遞給回傳的視圖。
我沒有錯誤,并且在我的腦海中這是有效的,但是由于某種原因,該變數沒有在控制器中重新評估。
這是我的剃須刀頁面:
@model securitypractice.Models.Article
@{
ViewData["Title"] = "Delete";
ViewData["Deletable"] = true;
}
<h1>Delete</h1>
@if((bool)ViewData["Deletable"]! == true)
{
<h3>Are you sure you want to delete this post?</h3>
<div>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Title)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.ArticleBody)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.ArticleBody)
</dd>
</dl>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
<input type="submit" value="Delete" class="btn btn-danger" /> |
<a asp-action="Index">Back to List</a>
</form>
</div>
} else if((bool)ViewData["Deletable"]! == false)
{
<div class="row">
<div class="col-sm-8">
<h2>Only the post author or moderator has the ability to delete a post.</h2>
<a asp-action="Index">Back to List</a>
</div>
</div>
}
這是我的控制器:
// GET: Articles/Delete/5
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var article = await _context.Articles
.FirstOrDefaultAsync(m => m.Id == id);
if (article == null)
{
return NotFound();
}
ViewData["Deletable"] = (User.Identity.Name == article.Author) ? true : false;
return View(article);
}
uj5u.com熱心網友回復:
ViewData["Deletable"] = true;從視圖頂部洗掉線。
這實際上將值分配給 true 并將覆寫從控制器發送的值。
旁白:在視圖中設定標題的原因是因為ViewData["Title"]在 _Layout.cshtml 模板中使用該值來為頁面提供適當的標題(盡管可以在控制器中分配它)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407652.html
標籤:
