0

我正在使用ASP.NET MVC 4最新的FluentValidation.

我正在努力让我的单选按钮进行验证。当我单击提交按钮时,我需要在单选按钮列表中进行选择。

在我看来,我有以下几点:

@model MyProject.ViewModels.Servers.ServicesViewModel
@Html.ValidationMessageFor(x => x.ComponentTypeId)
@foreach (var componentType in Model.ComponentTypes)
{
     <div>
          @Html.RadioButtonFor(x => x.ComponentTypeId, componentType.Id, new { id = "emp" + componentType.Id })
          @Html.Label("emp" + componentType.Id, componentType.Name)
     </div>
}

我的 ComponentType 类:

public class ComponentType : IEntity
{
     public int Id { get; set; }

     public string Name { get; set; }
}

我设置视图模型属性的操作方法的一部分:

ServicesViewModel viewModel = new ServicesViewModel
{
     ComponentTypes = componentTypeRepository.FindAll(),
     Domains = domainRepository.FindAll()
};

我的视图模型:

[Validator(typeof(ServicesViewModelValidator))]
public class ServicesViewModel
{
     public int ComponentTypeId { get; set; }

     public IEnumerable<ComponentType> ComponentTypes { get; set; }

     public int DomainId { get; set; }

     public IEnumerable<Domain> Domains { get; set; }
}

我的验证器类:

public class ServicesViewModelValidator : AbstractValidator<ServicesViewModel>
{
     public ServicesViewModelValidator()
     {
          RuleFor(x => x.ComponentTypeId)
               .NotNull()
               .WithMessage("Required");

          RuleFor(x => x.DomainId)
               .NotNull()
               .WithMessage("Required");
     }
}

我的 http Post 操作方法:

[HttpPost]
public ActionResult Services(ServicesViewModel viewModel)
{
     Check.Argument.IsNotNull(viewModel, "viewModel");

     if (!ModelState.IsValid)
     {
          viewModel.ComponentTypes = componentTypeRepository.FindAll();
          viewModel.Domains = domainRepository.FindAll();

          return View(viewModel);
     }

     return View(viewModel);
}

当没有选择任何内容时,如何让它显示我所需的消息?

4

1 回答 1

0

我认为问题在于您使用的是intforComponentId而不是 nullable int。然后,您将使用NotNull()永远不会触发的验证器,因为 anint不能为空。

尝试将其切换为:

[Validator(typeof(ServicesViewModelValidator))]
public class ServicesViewModel
{
     public int? ComponentTypeId { get; set; }

     public IEnumerable<ComponentType> ComponentTypes { get; set; }

     public int DomainId { get; set; }

     public IEnumerable<Domain> Domains { get; set; }
}

如果该剂量不起作用,那么您可以尝试使用范围验证:

public class ServicesViewModelValidator : AbstractValidator<ServicesViewModel>
{
     public ServicesViewModelValidator()
     {
          RuleFor(x => x.ComponentTypeId)
               .InclusiveBetween(1, int.MaxValue)
               .WithMessage("Required");

          RuleFor(x => x.DomainId)
               .NotNull()
               .WithMessage("Required");
     }
}

这将使 0 不是有效值。

于 2013-02-20T14:32:13.700 回答