首页 文章

具有 ValidationMessage 的复杂类型

提问于
浏览
2

我有一个需要内部化的项目。具体来说,我有一个名为“LocalizedString”的类,它包含特定文本的英语和德语翻译。

这看起来像这样:

[ComplexType]
 public class LocalizedString : IComparer, IComparable
 {
   public string EnglishText { get; set; }
   public string GermanText { get; set; }
// this is only an example - the real class has some methods to return the text in the current language.
     }

该类几乎用于我的所有域和视图模型,如下所示:

public class DemoItem
{
  public LocalizedString ItemDescription {get; set;}
}

最后,DemoItem 可能会像这样呈现:

@model Domain.Entities.DemoItem

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>DemoItem</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.ItemDescription , htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ItemDescription , new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ItemDescription , "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

现在问题是,EditorFor 方法将两个 text-boxes 渲染为 ItemDescription 的输入字段 - 这非常好,应该是这样的。但是如果有错误,e.g. 用户忘记输入德语描述,ValidationMessageFor()不起作用。或者更具体地说:没有错误显示给用户,因为回发提供的项目不是预期的格式。通过 ValidationSummary 显示所有错误,但不如错误元素旁边的错误那么好。

是否有一种简单的方法可以使 ValidationMessages 特定于违规元素?

1 回答

  • 1

    如果在 LocalizedString 类中为属性使用DataAnnotation属性,则验证消息将显示在有问题的元素旁边。

    我将验证属性添加到 GermanText 和 EnglishText,如下所示

    [Required]
        public string EnglishText { get; set; }
    
        [Required]
        public string GermanText { get; set; }
    

    并且能够看到违规元素旁边的验证消息。这样做我能够看到每个违规元素旁边的验证消息。

    我希望这会有所帮助。

相关问题