0

我有一个继承IValidatableObject了我的验证通过IEnumerable<ValidationResult>函数验证的类。在这个函数中,我设法检查所有字段并返回一条ValidationResult消息。

但是,我的问题是membernames.ToArray()只传递一个值。我在调试视图页面时证明了这一点,并在检查该字段是否有效时使用Html.ViewData.ModelState.IsValid("<fieldname>")

下面是当我返回包含所有无效字段的 ValidationResult 消息时的代码。将string.Join(",", membernames.ToArray())返回字段的集合。(即“名”、“姓”)

List<string> membernames = new List<string>();

//Firstname
if (FirstName.Trim() == string.Empty)
{
   isValid = false;
   membernames.Add(@"""FirstName""");
}

//Lastname
if (LastName.Trim() == string.Empty)
{
   membernames.Add(@"""LastName""");
   isValid = false;
}

if (!isValid)
{
    yield return new ValidationResult("Please complete all fields marked with *", new[] { string.Join(",", membernames.ToArray()) });
}

我是否传递了正确的类型new[] { .. }

请指教。提前致谢。

4

1 回答 1

0

In Mvc3 :

in Controller:

ModelState.AddModelError("FirstName", "FirstName Minimum 2 Char");
ModelState.AddModelError("FirstName", "FirstName Maximum 20 Char");
ModelState.AddModelError("LastName", "Error Message");

if You Want only one Error Message for All property:

ModelState.AddModelError("", "First Error Message");
ModelState.AddModelError("", "Second Error Message");

in View:

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

    @Html.LabelFor(model => model.FirstName)
    @Html.EditorFor(model => model.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName)

    @Html.LabelFor(model => model.LastName)
    @Html.EditorFor(model => model.LastName)
    @Html.ValidationMessageFor(model => model.LastName)

   //other fields...
}

don't forget jquery and Validation plugin:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
于 2012-05-19T15:29:12.020 回答