ViewData.ModelState.IsValid 检查一个 razor 视图中包含的所有(部分)表单的触发

ViewData.ModelState.IsValid check firing for all (partial) forms contained in one razor view

我的主页上有两个表格(一个联系表格和一个竞赛表格,都是部分表格),都有单独的控制器和模型。

在两个部分中,我都有以下代码,如果电子邮件发送失败,它会显示一条错误消息。

if (!ViewData.ModelState.IsValid)
{
    <div class="form-failure">
        <h4><i class="fa fa-close"></i>@Model.FailureTitle</h4>
        @Html.Raw(Model.FailureContent)
    </div>

两个控制器中的电子邮件错误代码

            if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
            {
                ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
                return CurrentUmbracoPage();
            }

问题是错误显示在两种形式上,因为 !ViewData.ModelState.IsValid returns 两者的结果相同。如何确保错误仅显示在提交请求的表单上?

}

你可以在ViewData中存储它是哪种形式

if (emailService.Send(EmailMessageBuilder.BuildUserEmail(model.FullName, model.EmailAddress, model.PhoneNumber)) != EmailState.Success)
{
    ViewData["Form"] = "Form1";
    ModelState.AddModelError("Email", "There was a problem sending the Email. Please try again later, or call us.");
    return CurrentUmbracoPage();
}

然后在html中查看哪个表格无效

if (!ViewData.ModelState.IsValid && ViewData["Form"] == "Form1" )
{
     ....
}