I am using ASP.NET MVC 4
and the latest FluentValidation
.
I am struggling to get my radio buttons to validate. When I click the submit button I need a selection in the radio button list.
In my view I have the following:
@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>
}
My ComponentType class:
public class ComponentType : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
Part of my action method where I set the properties of my view model:
ServicesViewModel viewModel = new ServicesViewModel
{
ComponentTypes = componentTypeRepository.FindAll(),
Domains = domainRepository.FindAll()
};
My view model:
[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; }
}
My validator class:
public class ServicesViewModelValidator : AbstractValidator<ServicesViewModel>
{
public ServicesViewModelValidator()
{
RuleFor(x => x.ComponentTypeId)
.NotNull()
.WithMessage("Required");
RuleFor(x => x.DomainId)
.NotNull()
.WithMessage("Required");
}
}
My http Post action method:
[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);
}
How do I get it to show my required message when nothing selected?