我正在尝试在一个简单的联系表单上实现数据验证和错误处理。当我添加 ModelState.IsValid
检查时,我陷入了进退两难的境地。我已经查看了其他类似的问题,但仍然无法理解。我正在从 Web Forms 转向 MVC,感到困难重重。我试图根据发生的情况切换 HTML 元素 - 成功/错误消息等等。目前甚至没有验证起作用。
目前我只是想使服务器端验证工作,但我很乐意听取如何添加客户端验证的建议;例如,是否需要使用 jQuery 进行此操作,还是有其他内置的选项?
视图:
@using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
if (ViewData["Error"] == null && ViewData["Success"] == null)
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
<div class="form-group">
<label class="sr-only" for="contact-email">Email</label>
<input type="text" name="email" placeholder="Email..."
class="contact-email" id="contact-email">
</div>
<div class="form-group">
<label class="sr-only" for="contact-subject">Subject</label>
<input type="text" name="subject" placeholder="Subject..."
class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label class="sr-only" for="contact-message">Message</label>
<textarea name="message" placeholder="Message..."
class="contact-message" id="contact-message"></textarea>
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
}
else if (ViewData["Error"] == null && ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to call
us at (xxx) xxx-xxxx at any time.
</p>
}
else if (ViewData["Error"] != null)
{
<h3>Oops!</h3>
<p>
We apologize. We seem to be having some problems.
</p>
<p>
Please come back and try again later. Alternatively,
call us anytime at (xxx) xxx-xxxx.
</p>
}
}
模型:
public class ContactModel
{
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Subject is required")]
public string Subject { get; set; }
[Required(ErrorMessage = "Message is required")]
public string Message { get; set; }
}
控制器:
[HttpPost]
public ActionResult Contact(ContactModel contactModel)
{
if (ModelState.IsValid)
{
try
{
MailMessage message = new MailMessage();
using (var smtp = new SmtpClient("mail.mydomain.com"))
{
// Standard mail code here
ViewData["Success"] = "Success";
}
}
catch (Exception)
{
ViewData["Error"]
= "Something went wrong - please try again later.";
return View("Error");
}
}
return View();
}
错误视图:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<hgroup>
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
</body>
</html>
更新-05/09/2017
根据Guruprasad的回答,如果ModelState.IsValid
评估为false,那么表单上没有报告验证错误消息。
注意:我不想向用户报告系统错误,因此必须更改AddModelError
签名以不使用“Extension ex”参数:ModelState.AddModelError("Error", "Server side error occurred");
还要注意,此时我仅在服务器端尝试验证(尚未解决客户端验证问题)。由于未显示任何模型错误,因此我已将Contact.cshtml视图更新如下-我已包括Bootstrap .has-error
和.help-block
CSS规则用于验证错误:
@using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
<div class="form-group has-error">
<label class="sr-only" for="contact-email">Email</label>
@Html.TextBoxFor(m => m.Email, new { type = "text", name = "email",
placeholder = "Email..", @class = "contact-email" })
@Html.ValidationMessageFor(model => model.Email, String.Empty,
new { @class="help-block" })
</div>
<div class="form-group has-error">
<label class="sr-only" for="contact-subject">Subject</label>
@Html.TextBoxFor(m => m.Subject, new { type = "text",
name = "subject",
placeholder = "Subject..", @class = "contact-subject" })
@Html.ValidationMessageFor(model => model.Subject, String.Empty,
new { @class = "help-block" })
</div>
<div class="form-group has-error">
<label class="sr-only" for="contact-message">Message</label>
@Html.TextAreaFor(m => m.Message, new { name = "message",
placeholder = "Message..", @class = "contact-message" })
@Html.ValidationMessageFor(model => model.Message, String.Empty,
new { @class = "help-block" })
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
if (ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to
call us at (xxx) xxx-xxxx at any time.
</p>
}
}
ModelState.IsValid
为 false 时,有什么错误存在?另外,如果你不想让系统错误报告给用户,那么可以在 web.config 文件中进行配置,在其中为不同的错误代码设置自定义视图。另外,请查看ExceptionFilter
,你可以扩展它以显示不同的自定义视图来处理不同类型的错误。如果你在这方面遇到任何问题,请告诉我。 - Guruprasad J Rao