gpt4 book ai didi

asp.net - ASP.NET MVC 5表单验证和错误处理

转载 作者:行者123 更新时间:2023-12-02 21:25:37 26 4
gpt4 key购买 nike

尝试在简单的联系表单上实现数据验证和错误处理。当我添加ModelState.IsValid的支票时,我处于鸡肉和鸡蛋的状况。我看过其他类似的问题,但还没有明白。从Web窗体过渡到MVC并陷入困境。尝试根据发生的事情切换HTML元素-成功/错误消息等。现在,甚至验证都无法正常进行。

现在,我只是在尝试使服务器端验证有效,但也欢迎您就如何添加客户端验证提出建议。例如,是否需要为此使用jQuery或其中包含某些东西?

View :

@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; }
}

Controller :
[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();
}

错误 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>

更新-2017/05/09

根据Guruprasad的回答,如果 ModelState.IsValid评估为false,则在表单上未报告任何验证错误消息。

注意我必须更改 AddModelError签名以不使用“Extension ex”参数: ModelState.AddModelError("Error", "Server side error occurred");,因为我不希望向用户报告系统错误。

另请注意,这时我仅在服务器端尝试验证(尚未通过客户端验证进行工作)。
我已经更新了Contact.cshtml View ,如下所示,因为未显示任何模型错误-我包括了验证错误的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>
}
}

最佳答案

您需要在这里了解很多事情。让我一点一点走。

  • 很高兴知道您已经设计了自己的model,但是您的 View 如何知道它具有要绑定(bind)的model,并且在发布form内容时,server如何得知,有一个model可以接收。因此,首先,您需要绑定(bind)model来构建 View 。要将model绑定(bind)到view中,您需要首先在顶部获得一个引用/声明,让 View 知道,好的,这是一个model供您生成我的view
  • 好吧,您将ValidationSummary设置为true,那么我建议,可以使用ViewData代替ModelState.AddModelError传递错误消息,而让ValidationSummary来解决此问题。附带说明,您可能还需要照顾 this issue ,并且可以使用同一篇文章中提到的答案来解决同样的问题。如果您不使用或不想使用Html.ValidationSummary,则可以坚持使用当前 View 。
  • 现在,要显示Success消息,您可以使用TempDataViewData并遵循与现在 View 相同的结构。这是 one more post ,可让您进行处理。
  • View部分的最后也是最重要的是将model属性绑定(bind)到View元素。使用Razor View扩展助手来为View生成model。您有@Html.TextBoxFor@Html.TextAreaFor等,您也有@Html.TextBox@Html.TextArea,它们不用于绑定(bind)model properties,而仅用于生成普通的HTML view。您可以在这些html中添加其他helpers属性,如下面更新的view中所示。我建议进一步挖掘这些助手可用的重载。

  • 这是您的更新 View 。
    @model SOTestApplication.Models.ContactModel   @*getting model reference*@

    @using (Html.BeginForm("Contact", "Home", FormMethod.Post))
    {
    <h3>Send us an email</h3>
    Html.ValidationSummary(true);
    <div class="form-group">
    <label class="sr-only" for="contact-email">Email</label>
    @Html.TextBoxFor(m => m.Email, new { type = "text", name = "email", placeholder = "Email..", @class = "contact-email" })
    @*Usage of helpers and html attributes*@
    </div>
    <div class="form-group">
    <label class="sr-only" for="contact-subject">Subject</label>
    @Html.TextBoxFor(m => m.Subject, new { type = "text", name = "subject", placeholder = "Subject..", @class = "contact-subject" })
    </div>
    <div class="form-group">
    <label class="sr-only" for="contact-message">Message</label>
    @Html.TextAreaFor(m => m.Message, new { name = "message", placeholder = "Message..", @class = "contact-message" })
    </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>
    }

    Controller 端验证

    在这部分上没有太多要说的,因为它看起来不错。但是基于以上几点,我建议您添加 ModelState.AddModelError而不是使用 ViewData来显示错误消息。消除 View 中的 if条件,即使在 postback之后,也保留 联系表。现在,如果要在 server side验证后保留这些值,则只需将 model传递回 view方法中的 post。更新的 Controller将为:
    [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)
    {
    ModelState.AddModelError("Server side error occurred", ex.Message.ToString());
    }
    }
    return View(contactModel); //this will persist user entered data on validation failure
    }

    客户端验证

    就此部分而言,您在应用程序中还需要设置其他内容。
  • 您需要在应用程序中添加Html.EnableClientValidation(true);Html.EnableUnobtrusiveJavaScript(true);。有多种可能的方法可以添加此内容。您可以将其添加到Web.config下的appSettings文件中以获得全局含义,也可以按照以下更新的view示例中的说明将其添加到特定的View中。

  • Web.Config中的全局含义,例如:
    <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
  • 如果您注意到 App_Start 目录下的BundleConfig.cs文件,则可能会看到以下默认创建的条目。这些是负责客户端验证的jquery内容。

  • jQueryjQueryVal条目
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    "~/Scripts/jquery-{version}.js"));
    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
    "~/Scripts/jquery.unobtrusive*",
    "~/Scripts/jquery.validate*"));
  • 下一步是添加对这些文件的引用/使用@section Scriptsbundles或任何特定的_Layout.cshtml呈现这些view。当您将其包含在_Layout.cshtml中时。只要您将此layout与其他 View 一起使用,这些脚本/文件包就会呈现。因此,基本上,您可以在哪里渲染这些内容。

  • 例如,在这里,我将在添加对 Contact.cshtml view的引用后立即在 model中呈现这些内容。
    @section Scripts
    {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    }
  • 在这里要完成此工作的最后一件事是,您需要使用@Html.ValidationMessageFor Razor 扩展名,并让MVC在特定属性上绑定(bind)错误消息。同样,要使这些错误消息显示在View中,您还需要为ErrorMessage 中的每个属性指定model,因为现在您需要为Required(ErrorMessage=...中的每个属性指定model。如果您对其进行详细研究,则还有更多关于这些东西的知识。

  • 您添加了正确验证的更新 View 。
    @model SOTestApplication.Models.ContactModel
    @section Scripts
    {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    }
    @using (Html.BeginForm("Contact", "Contacts", FormMethod.Post))
    {

    <h3>Send us an email</h3>
    Html.ValidationSummary(true);
    Html.EnableClientValidation(true);
    Html.EnableUnobtrusiveJavaScript(true);
    <div class="form-group">
    <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(m => m.Email)
    </div>
    <div class="form-group">
    <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(m => m.Subject)
    </div>
    <div class="form-group">
    <label class="sr-only" for="contact-message">Message</label>
    @Html.TextAreaFor(m => m.Message, new { name = "message", placeholder = "Message..", @class = "contact-message" })
    @Html.ValidationMessageFor(m => m.Message)
    </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>
    }
    }

    希望我已就这些观点澄清了您的大部分疑问。快乐编码.. :)

    关于asp.net - ASP.NET MVC 5表单验证和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41687545/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com