我有一个这样的约会课程:
public class Appointment
{
public string ClientName { get; set; }
public DateTime Date { get; set; }
}
在HomeController
中:
public IActionResult Index()
{
return View(new Appointment { Date = DateTime.Now }); //first time to get the form
}
,默认的index.cshtml
内部有一个表单,并显示客户端名称和日期,当按下“提交”按钮时,它将值发布到MakeBooking
操作方法中,如下所示:
public ViewResult MakeBooking(Appointment appt)
{
return View(); // second time to get the form
}
我不明白的是,我运行了应用程序,并在表单中填充了一些值,例如,客户名称为“ Michael”,日期为“ 20/08/2019”,然后按了提交按钮,定向到MakeBooking
动作方法,在该动作方法中,我返回了一个没有数据模型的视图。因此第二次,该表单应该没有任何价值,因为我没有在视图中传递数据模型appt
,但是为什么我仍然在视图中填充了“ Michael”和“ 20/08/2019” ?
这是index.cshtml
:
@model Appointment
@{ Layout = "_Layout"; }
<form class="m-1 p-1" asp-action="MakeBooking" method="post">
<div class="form-group">
<label asp-for="ClientName">Your name:</label>
<input asp-for="ClientName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Date">Appointment Date:</label>
<input asp-for="Date" type="text" asp-format="{0:d}" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Make Booking</button>
</form>
答案 0 :(得分:4)
HTML帮助器实际上会在查看模型状态之前在模型状态中检查要显示在字段中的值。在控制器中使用它
ModelState.Clear();
return View();