[英]Why asp-for input tag helper always use form data instead of the viewmodel?
我的目標是,當提交表單時,能夠再次顯示表單,但使用修改后的模型,我替換了一些值。
以這個簡化的代碼為例:
public class IndexController : Controller
{
[HttpGet("")]
public IActionResult Index()
{
return View(new IndexViewModel() { Origin = "GET" });
}
[HttpPost("")]
public IActionResult Index(IndexViewModel viewModel)
{
viewModel.Origin = "POST";
viewModel.Name = "Fixed Name"; // I want to force this value
return View(viewModel);
}
}
public class IndexViewModel
{
public string Name { get; set; }
public string Origin { get; set; }
}
以下視圖:
@model IndexViewModel
<html>
<body>
<form method="post">
Name : <input asp-for="Name" /><br />
Origin : @Model.Origin
<br />
<button type="submit">Submit</button>
</form>
</body>
</html>
當我提交表單時,該方法通過 POST 方法,但視圖 HTML 僅使用原始表單值。
渲染視圖時,值“固定名稱”將被忽略且從不使用。
我想asp-for
標簽助手總是給予FormCollection
值更高的優先級。 有沒有辦法強制使用 Model 值?
我無法回答為什么會發生這種情況,可能知識淵博的人可以回答,但我不得不使用Post-Redirect-Get模式:
[HttpPost("")]
public IActionResult Index(IndexViewModel viewModel)
{
viewModel.Origin = "POST";
// persist model or use TempData
return RedirectToAction("AfterPost");
}
public IActionResult AfterPost()
{
// get model or retrieve from TempData
viewModel.Name = "Fixed Name"; // I want to force this value
return View(viewModel);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.