【问题标题】:Why returning a new view doesn't reset form为什么返回新视图不会重置表单
【发布时间】:2019-08-20 05:24:39
【问题描述】:

我有一个这样的约会课程:

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 action 方法,在action 方法里面,我返回了一个没有数据模型的视图。所以第二次,表单应该没有任何价值,因为我没有在视图中传递数据模型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>

【问题讨论】:

  • 请提供您的html内容
  • @NijinKoderi 我已经添加了
  • You're running into this problem。 TLDR:在调用 View() 之前,在您的第二个操作中使用 ModelState.Clear();

标签: c# asp.net-mvc asp.net-core-mvc


【解决方案1】:

Html Helpers 在查看 Model 之前实际上会在 ModelState 中检查要在字段中显示的值。在控制器中使用它

ModelState.Clear();
return View();

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多