在 asp.net mvc 5 中制作复选框列表自定义验证

Making checkboxlist custom validation in asp.net mvc 5

我正在开发一个 ASP.Net MVC 5 Web 应用程序,但在对复选框列表进行自定义验证时遇到了一些困难。验证我需要至少选中一个复选框

我的视图模型

public class EditUtilisateurViewModel
{
public long Id { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = " Required ")]
[Display(Name = "Login")]
public string UserName { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = "Required")]
[Display(Name = "Email")]
[EmailAddress (ErrorMessage = "Invalid Email")]
public string Email { get; set; }

[CheckOneSelected(ErrorMessage = "Please select role")]
public IEnumerable<System.Web.Mvc.SelectListItem> RolesList { get; set; }

}

我的控制器

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,UserName,Email")] EditUtilisateurViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
    // ToDo ...

    return RedirectToAction("Index");
}
}

我的观点

@model MyProject.Areas.Admin.Models.EditUtilisateurViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(m => m.Id)
    <table
        <tbody>
            < >
                <th>
                    @Html.LabelFor(m => m.UserName)
                </th>
                <td>
                    @Html.TextBoxFor(m => m.UserName)
                    @Html.ValidationMessageFor(m => m.UserName)
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Email)
                </th>
                <td>
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @disabled = "disabled" })
                    @*@Html.ValidationMessageFor(m => m.Email)*@
                </td>
            </tr>
            <tr>
                <th>@Html.Label("Roles")</th>
                <td>
                    <span>
                        @foreach (var item in Model.RolesList)
                        {
                            @*<input type="checkbox" id="@item.Value" name="SelectedRole" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />*@
                            @Html.CheckBoxFor(m => item.Selected, new { id = item.Value, @Value = item.Value, @Name = "selectedRole[]", @class = "checkbox-inline", data_val = "true", data_val_verifListe = " Select field " })
                            @Html.Label(item.Value, new { @class = "checkbox-inline-label" })
                        }
                    </span>
                    @Html.ValidationMessageFor(m => m.RolesList)
                </td>
            </tr>
        </tbody>
    </table>
    <p>
        <input type="submit" value="Update" />
    </p>
}

我尝试了如下所示的验证,但遇到了问题

namespace ...
{
    public class CheckOneSelectedAttribute : ValidationAttribute, IClientValidatable
    {
        public string[] SelectedRole { get; private set; }

        public CheckOneSelectedAttribute(string SelectedValue) : base("Select field")
        {
            if (SelectedValue != null && SelectedValue.Length > 0)
                SelectedRole = SelectedValue;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                if (selectedRole != null)
                {
                    if (selectedRole.Length == 0)
                    {
                        return new ValidationResult("Select field ");
                    }
                }
            }
            else
            {
                return new ValidationResult("Null parameter");
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule()
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "CheckOneSelected"
            };
        }
    }
}

有人可以帮助我吗? 谢谢。

在 post 和 []list 的控制器部分,您应该检查列表的长度,以便您可以对其进行验证。