implement validation in asp.net mvc
https://www.theitroad.com
To implement validation in ASP.NET MVC, you can follow these steps:
- Create a model class with the properties you want to validate. For example:
public class Person {
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(0, 120)]
public int Age { get; set; }
}
- In your controller, add a
[HttpPost]action method to handle form submissions. This method should accept an instance of your model as a parameter. For example:
[HttpPost]
public ActionResult Create(Person person) {
if (ModelState.IsValid) {
// Save person to database
return RedirectToAction("Index");
}
return View(person);
}
- In your view, add validation messages to display errors to the user. For example:
@model Person
@using (Html.BeginForm()) {
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
@Html.LabelFor(m => m.Age)
@Html.TextBoxFor(m => m.Age)
@Html.ValidationMessageFor(m => m.Age)
<input type="submit" value="Save" />
}
- In your
Web.configfile, make sure theclientValidationEnabledandunobtrusiveJavaScriptEnabledsettings are set totrue. For example:
<appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>
These steps will enable client-side and server-side validation for your ASP.NET MVC application. If the model validation fails, the validation messages will be displayed to the user, and the form will not be submitted.
