我正在开发一个ASP.Net MVC 5 Web应用程序,我在Checkbox列表上进行自定义验证时遇到了一些困难。验证我需要至少检查一个复选框
我的ViewModel
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"
};
}
}
}
有人可以帮帮我吗? 感谢。
答案 0 :(得分:1)
在post和take []列表的控制器部分中,你应该检查列表的长度,你可以对其进行验证。