Home > DeveloperSection > Forums > How can we do validations in MVC?
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    February-07-2016 10:07 PM

 ASP.Net C#  ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 403  View(s)
Rate this:
Hi Everyone,
Please give me a example, how to apply validation in ASP.NET MVC 4.Can anyone give me a solution.

Thank you.


Anupam Mishra

Total Post:135

Points:949
Posted on    February-07-2016 11:26 PM

We are implementing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, we have a simple Student class with a property StudentFullName.
This StudentFullName property is tagged with a Required data annotation attribute. In other words if this model is not provided Student FullName, it will not accept it.

public class Student
{
    [Required(ErrorMessage=" Student FullName is required")]
    public string StudentFullName
    {
        set;
        get;
    } 
}  

For display of validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

@using (Html.BeginForm("StudentFullName", "Home", FormMethod.Post))

@Html.TextBoxFor(m => m. StudentFullName)
@Html.ValidationMessageFor(m => m. StudentFullName)
.....
}

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

public ActionResult StudentFullName(Student obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Save Sucessfully");
    }
    else
    {
        return View("Student");
    }
}

Modified On Feb-08-2016 09:53:50 PM

Don't want to miss updates? Please click the below button!

Follow MindStick