gpt4 book ai didi

c# - 具有 ValidationMessage 的复杂类型

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:23 25 4
gpt4 key购买 nike

我有一个项目需要一些内部化。具体来说,我有一个名为“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.
}

这个类几乎在我所有的域和 View 模型中都使用过,如下所示:

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 方法将两个文本框呈现为 ItemDescription 的输入字段 - 这非常好,应该如下所示。但是如果有错误,例如用户忘记输入德语描述,ValidationMessageFor() 不起作用。或者更具体地说:没有错误显示给用户,因为回发提供的项目不是预期的格式。通过 ValidationSummary 显示所有错误是可行的,但不如错误元素旁边的错误好。

是否有一种简单的方法来获取特定于违规元素的 ValidationMessages?

最佳答案

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

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

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

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

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

我希望这会有所帮助。

关于c# - 具有 ValidationMessage 的复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526978/

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