I am new to ASP.NET MVC. I am trying to validate some user input. The model behind my view looks like this:
public class ViewModel
{
[Required]
public int? Minimum { get; set; }
[Required]
public int? Maximum { get; set; }
}
My View (.cshtml file) looks like this
@model Website.Models.ViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
...
<div class="row">
<div class="col-sm-6"><input class="form-control input-sm" id="Minimum" name="Minimum" type="text" /></div>
<div class="col-sm-6"><input class="form-control input-sm" id="Maximum" name="Maximum" type="text" /></div>
</div>
...
<br />
<button type="submit" class="btn btn-primary">Save</button>
}
My controller, looks like this:
public class MyController
{
public ActionResult Edit(int? id)
{
var model = new ViewModel();
return View(model);
}
[HttpPost]
public ActionResult Edit(ViewModel model)
{
if (ModelState.IsValid) {
var result = await model.SaveAsync();
return RedirectToAction("Edit", new { id = result.DemandId, u = "true" });
}
return View(model);
}
}
My code is validating whether the field is provided or not. However, I need to add some business rules. For instance, I need to ensure that Maximum is more than Minimum. If it is not, then I need to give the user an error. I intend to have even more complicated validation scenarios.
My question is, how should I handle these advanced validation scenarios in ASP.NET MVC?
MinimumandMaximumnullable if they're required?[GreaterThan("Minimum")]to give you client and server side validation (but you need to generate the controls correctly using@Html.TextBoxFor()and@Html.ValidationMessageFor()