【问题标题】:How to include the value of one attribute in the validation error message of another?如何在另一个属性的验证错误消息中包含一个属性的值?
【发布时间】:2012-11-27 13:08:28
【问题描述】:

我有一份问卷,其中包含多页的 12 条语句,用户必须为每个语句指定语句与它们匹配的程度。看起来像这样:

我的视图模型如下所示:

public class PageViewModel
{
    public List<ItemViewModel> Items { get; set; }
}

public class ItemViewModel
{
    public Guid Id { get; set; }
    public int Number { get; set; }
    public string Text { get; set; }

    [Required]
    public int Response { get; set; }
}

我的看法:

@model PageViewModel

@using(Html.BeginForm()){
<table>
    <tr>
        <td></td>
        <td></td>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
        <th>5</th>
    </tr>

    @Html.EditorFor(model => model.Items)

    @Html.ValidationSummary(false)

</table>

<input type="submit"/>
}

并且编辑器模板为每个项目重复:

@model ItemViewModel

<tr>
    <td>@Model.Number:</td>
    <td>@Model.Text</td>

    @for(int i = 1; i <= 5; i++){
        <td>@Html.RadioButtonFor(model => model.Response, i)</td>
    }
<tr>

我希望验证摘要能列出需要回复的语句,例如。 “声明 6 需要答复”。目前它只是重复“需要响应字段”

我应该想象需要一个自定义验证器,但目前从头开始编写我自己的验证器有点超出我的能力,因此我们将不胜感激。

【问题讨论】:

    标签: asp.net-mvc-3 validation data-annotations


    【解决方案1】:

    您需要编写自己的Custom Validation Summary Template

    namespace System.Web.Mvc
    {
        public static class ViewExtensions
        {
            public static string MyValidationSummary(this HtmlHelper html, string validationMessage)
            {
                if (!html.ViewData.ModelState.IsValid)
                {
                    return "customized message from here";
                }
    
                return "";
            }
        }
    }
    

    另请参阅 - How to extend the ValidationSummary HTML Helper in ASP.NET MVC?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多