我知道下面的 post action 方法是反模式的,但我仍然假設看到一個 Name 設定為 null 的新頁面。但是當我點擊提交按鈕時,頁面沒有重新加載,我仍然看到舊名稱顯示,這是瀏覽器的問題還是 asp.net 核心框架的問題?
public class HomeController : Controller
{
private IRepository repository;
public HomeController(IRepository repo)
{
repository = repo;
}
// ...
public IActionResult Create() // create a Employer that has a name in the browser
{
return View();
}
[HttpPost]
public IActionResult Create(Employee model)
{
model.Name = ""; // <----------------set it to null so I expect to see the Name being empty in the reponse
return View(model);
}
}
// view file, Create.cshtml:
@model Employee
@{
ViewData["Title"] = "Create Employee";
}
<h2>Create Employee</h2>
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Id"></label>
<input asp-for="Id" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="DOB"></label>
<input asp-for="DOB" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Role"></label>
<select asp-for="Role" class="form-control" asp-items="@new SelectList(Enum.GetNames(typeof(Role)))"></select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
首先,呼叫 Create() 操作方法并填充一些資料的 get 方法:

單擊提交按鈕后,頁面仍然顯示原始名稱,但我希望看到一個空名稱,因為我在發布操作方法中對其進行了修改

那么為什么在第二次請求后名稱仍然存在?
uj5u.com熱心網友回復:
那么為什么第二次請求后名稱仍然存在呢?
好吧,雖然,你有rebind你的model property value. 然而,你的current model state依舊不變。因此,即使在form resubmission. 要解決此問題,請嘗試以下代碼片段:
解決方案:

ModelState.Clear();將徹底解決您的問題。
uj5u.com熱心網友回復:
它可以重置您已回應的資料。所以基本上發送資料沒有任何損失
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533362.html
