ASP.NET MVC Html.ValidationSummary(true) 不显示模型错误

发布于 2024-09-01 10:22:49 字数 2329 浏览 4 评论 0原文

我对 Html.ValidationSummary 有一些问题。我不想在 ValidationSummary 中显示属性错误。当我设置 Html.ValidationSummary(true) 时,它不会显示来自 ModelState 的错误消息。当字符串捕获部分的控制器操作出现异常时,

MembersManager.RegisterMember(member);

会向 ModelState 添加错误:

ModelState.AddModelError("error", ex.Message);

但 ValidationSummary 不会显示此错误消息。当我设置 Html.ValidationSummary(false) 时,所有消息都会显示,但我不想显示属性错误。我该如何解决这个问题?

这是我正在使用的代码:

模型:

public class Member
{
        [Required(ErrorMessage = "*")]
        [DisplayName("Login:")]
        public string Login { get; set; }

        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [DisplayName("Password:")]
        public string Password { get; set; }

        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [DisplayName("Confirm Password:")]
        public string ConfirmPassword { get; set; }
}

控制器:

[HttpPost]
public ActionResult Register(Member member)
{
    try
    {
        if (!ModelState.IsValid)
            return View();

        MembersManager.RegisterMember(member);
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("error", ex.Message);

        return View(member);
    }
}

视图:

<% using (Html.BeginForm("Register", "Members", FormMethod.Post, 
                        new { enctype = "multipart/form-data" })) {%> 
    <p>
        <%= Html.LabelFor(model => model.Login)%>
        <%= Html.TextBoxFor(model => model.Login)%>
        <%= Html.ValidationMessageFor(model => model.Login)%>
    </p>

    <p>
        <%= Html.LabelFor(model => model.Password)%>
        <%= Html.PasswordFor(model => model.Password)%>
        <%= Html.ValidationMessageFor(model => model.Password)%>
    </p>

    <p>
        <%= Html.LabelFor(model => model.ConfirmPassword)%>
        <%= Html.PasswordFor(model => model.ConfirmPassword)%>
        <%= Html.ValidationMessageFor(model => model.ConfirmPassword)%>
    </p>

    <div>
        <input type="submit" value="Create" />
    </div>

    <%= Html.ValidationSummary(true)%>
<% } %>

I have some problem with Html.ValidationSummary. I don't want to display property errors in ValidationSummary. And when I set Html.ValidationSummary(true) it does not display error messages from ModelState. When there is some Exception in controller action on string

MembersManager.RegisterMember(member);

catch section adds an error to the ModelState:

ModelState.AddModelError("error", ex.Message);

But ValidationSummary does not display this error message. When I set Html.ValidationSummary(false) all messages are displaying, but I don't want to display property errors. How can I fix this problem?

Here is the code I'm using:

Model:

public class Member
{
        [Required(ErrorMessage = "*")]
        [DisplayName("Login:")]
        public string Login { get; set; }

        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [DisplayName("Password:")]
        public string Password { get; set; }

        [Required(ErrorMessage = "*")]
        [DataType(DataType.Password)]
        [DisplayName("Confirm Password:")]
        public string ConfirmPassword { get; set; }
}

Controller:

[HttpPost]
public ActionResult Register(Member member)
{
    try
    {
        if (!ModelState.IsValid)
            return View();

        MembersManager.RegisterMember(member);
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("error", ex.Message);

        return View(member);
    }
}

View:

<% using (Html.BeginForm("Register", "Members", FormMethod.Post, 
                        new { enctype = "multipart/form-data" })) {%> 
    <p>
        <%= Html.LabelFor(model => model.Login)%>
        <%= Html.TextBoxFor(model => model.Login)%>
        <%= Html.ValidationMessageFor(model => model.Login)%>
    </p>

    <p>
        <%= Html.LabelFor(model => model.Password)%>
        <%= Html.PasswordFor(model => model.Password)%>
        <%= Html.ValidationMessageFor(model => model.Password)%>
    </p>

    <p>
        <%= Html.LabelFor(model => model.ConfirmPassword)%>
        <%= Html.PasswordFor(model => model.ConfirmPassword)%>
        <%= Html.ValidationMessageFor(model => model.ConfirmPassword)%>
    </p>

    <div>
        <input type="submit" value="Create" />
    </div>

    <%= Html.ValidationSummary(true)%>
<% } %>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

客…行舟 2024-09-08 10:22:50

你可以尝试,

<div asp-validation-summary="All" class="text-danger"></div>

You can try,

<div asp-validation-summary="All" class="text-danger"></div>
已下线请稍等 2024-09-08 10:22:50

use 可以使用下面的行

    @if (!ViewData.ModelState.IsValid)
                {
                    @Html.ValidationSummary("", new { @class = "alert alert-warning alert-dismissible fade show" })
                }

,并且对于每个字段使用如下所示的内容:

                    @Html.ValidationMessageFor(m => m.Email, null, new { @class = "field-validation-error " })

use can use bellow lines

    @if (!ViewData.ModelState.IsValid)
                {
                    @Html.ValidationSummary("", new { @class = "alert alert-warning alert-dismissible fade show" })
                }

and for each field use somthing like this:

                    @Html.ValidationMessageFor(m => m.Email, null, new { @class = "field-validation-error " })
酷遇一生 2024-09-08 10:22:50

将其添加到视图的最下部分:

@section 脚本{
@Scripts.Render("~/bundles/jqueryval") }

ADD it in the lowermost part og your View:

@section Scripts {
@Scripts.Render("~/bundles/jqueryval") }

暗藏城府 2024-09-08 10:22:49

我相信 ValidationSummary 标志的工作方式是它只会显示 string.empty 作为键的 ModelErrors。否则,假定这是一个属性错误。您添加的自定义错误具有“error”键,因此当您调用 ValidationSummary(true) 时它不会显示。您需要使用空键添加自定义错误消息,如下所示:

ModelState.AddModelError(string.Empty, ex.Message);

I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:

ModelState.AddModelError(string.Empty, ex.Message);
旧伤还要旧人安 2024-09-08 10:22:49

这效果更好,因为您可以显示指定键的validationMessage:

    ModelState.AddModelError("keyName","Message");

并像这样显示它:

    @Html.ValidationMessage("keyName")

This works better, as you can show validationMessage for a specified key:

    ModelState.AddModelError("keyName","Message");

and display it like this:

    @Html.ValidationMessage("keyName")
看透却不说透 2024-09-08 10:22:49

我知道这有点旧了,并且已被标记为有 147 票赞成的答案,但还有其他事情需要考虑。

如果需要,您可以将所有模型错误、命名属性和 string.Empty 键等显示在 ValidationSummary 中。 ValidationSummary 中有一个重载可以执行此操作。

    //   excludePropertyErrors:
    //   true to have the summary display model-level errors only, or false to have
    //   the summary display all errors.
    public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors);

在此处输入图像描述

I know this is kind of old and has been marked as answers with 147 up votes, but there is something else to consider.

You can have all the model errors, the property named and string.Empty keys alike, be shown in the ValidationSummary if you need to. There is an overload in the ValidationSummary that will do this.

    //   excludePropertyErrors:
    //   true to have the summary display model-level errors only, or false to have
    //   the summary display all errors.
    public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors);

enter image description here

追风人 2024-09-08 10:22:49

也许像这样:

[HttpPost]
public ActionResult Register(Member member)
{
    try
    {
       if (!ModelState.IsValid)
       {
          ModelState.AddModelError("keyName", "Form is not valid");
          return View();
       }
       MembersManager.RegisterMember(member);
    }
    catch (Exception ex)
    {
       ModelState.AddModelError("keyName", ex.Message);
       return View(member);
    }
}

并在显示中添加:

<div class="alert alert-danger">
  @Html.ValidationMessage("keyName")
</div>

<div class="alert alert-danger">
  @Html.ValidationSummary(false)
</div>

Maybe like that:

[HttpPost]
public ActionResult Register(Member member)
{
    try
    {
       if (!ModelState.IsValid)
       {
          ModelState.AddModelError("keyName", "Form is not valid");
          return View();
       }
       MembersManager.RegisterMember(member);
    }
    catch (Exception ex)
    {
       ModelState.AddModelError("keyName", ex.Message);
       return View(member);
    }
}

And in display add:

<div class="alert alert-danger">
  @Html.ValidationMessage("keyName")
</div>

OR

<div class="alert alert-danger">
  @Html.ValidationSummary(false)
</div>
江南月 2024-09-08 10:22:49
@Html.ValidationSummary(false,"", new { @class = "text-danger" })

使用这条线可能会有所帮助

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful

°如果伤别离去 2024-09-08 10:22:49

就我而言,由于退货而无法正常工作。

使用:而是

return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });

我没有

return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });

使用: It´sa Model,因此很明显 ModelState.AddModelError("keyName","Message"); 必须与模型一起使用。

这个答案说明了原因。
使用 DataAnnotations 添加验证

In my case it was not working because of the return.

Instead of using:

return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });

I used:

return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });

It´s a Model, so it is obvius that ModelState.AddModelError("keyName","Message"); must work with a model.

This answer show why.
Adding validation with DataAnnotations

古镇旧梦 2024-09-08 10:22:49

如果几乎一切看起来都正确,那么需要注意的另一件事是确保验证摘要没有通过某些 CSS 覆盖显式隐藏,如下所示:

.validation-summary-valid {
    display: none;
}

这也可能导致 @Html.ValidationSummary 显示隐藏,因为摘要是使用 validation-summary-valid 类动态呈现的。

If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:

.validation-summary-valid {
    display: none;
}

This may also cause the @Html.ValidationSummary to appear hidden, as the summary is dynamically rendered with the validation-summary-valid class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文