Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Use validation on CheboxList in Asp.Net MVC4

$
0
0
Hi Laurent

Yes, it is certainly possible to do this kind of validation. As I mentioned before, you'll need to represent your checkbox list as part of your model. You'd then render this in your view. You can then post back the selected items as a property of your viewmodel, which can be passed to a validator. I can't provide you with a full example, but here's a simplistic example that hopefully illustrates the point.
 public class MyModel {
  public SelectList Sports { get; set; }
  public IEnumerable<string> SelectedSports { get; set; }
  
  public MyModel() {
    Sports = new SelectList(new[] { "Tennis", "Football", "Hockey" });
  } 
}
...in your view, you'd iterate over the Sports property to build the checkbox list:
<form method="post" action="">
  @foreach(var sport in Model.Sports) {
    <input type="checkbox" name="SelectedSports" value="@sport" />@sport <br />
  }
  <input type="submit" value="Submit" />
</form>
Validator:
public class MyModelValidator : AbstractValidator<MyModel> {
  public MyModelValidator() {
    RuleFor(x => x.SelectedSports).Must(x => x != null && x.Count() > 0).WithMessage("Please select at least 1 sport");
  }
}
Controller:
public class MyController : Controller 
  public ActionResult Index() {
    return View(new MyModel());
  }
  
  [HttpPost]
  public ACtionResult Index(MyModel model) {
     var validator = new MyModelValidator();
     var results = validator.Validate(model);
     // ... check whether results are valid, if not, re-render view etc etc
  }
}

Viewing all articles
Browse latest Browse all 1917

Trending Articles