【发布时间】:2021-09-13 16:17:02
【问题描述】:
我正在开发 asp.net core mvc web 应用程序。在我的控制器中,有两个名为“Index”和“Index2”的操作。
当我向“Index2”提交表单时,它将返回View("Index", model)。但是视图没有正确渲染。
例如,如果我在 TextBox 中输入“Steven”并提交到“Index2”操作,则 Name 属性应为“Name999”。 HTML 上的文本框应该显示“Name999”,但实际上,它仍然显示“Steven”。
代码示例:
@model WebApplication2.Controllers.Test
<form method="post" action="/home/Index2">
<div class="form-group">
<input type="text" asp-for="Name"/>
</div>
<div class="form-group">
<button type="submit">Add</button>
</div>
</form>
public IActionResult Index(Test test)
{
return View(test);
}
[HttpPost]
public IActionResult Index2(Test test)
{
test.Name = "Name999";
return View("Index",test);
}
public class Test
{
public string Name { get; set; }
}
【问题讨论】:
-
请解释一下但是视图渲染不正确,请。
-
我添加了更多信息。
-
看这个答案,stackoverflow.com/questions/26062359/… 简而言之,
The editors like TextBoxFor, DropDownListFor, etc. use the ModelState values instead of the values from the model you passed to the view. -
您可以尝试在 CSHTML 视图中将模型成员声明为隐藏变量(就在 @model 声明之后)。像这样:@Html.HiddenFor(x => x.Name);这应该通过视图绑定器绑定模型的会话变量。
标签: c# asp.net-core-mvc