MVC Form Validation using Model Class

     In previous chapter we did form submission and getting form data.In previous section we didn't apply any validations for our form.So if we enter any nonsense data or even without data also we can submit.This is not a good practice.
   
     Now we going to add validations for our form application. MVC provides a better approach for validations in domain model rather than using user interface.By using MVC model validation attributes we can restrict what type of data we want for particular filed.These model validation attributes is found under System.ComponentModel.DataAnnotations namespace.

    Now we are going to apply model validations for our Student model like below.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace FirstMVCApplication.Models
{
    public class Student
    {
        [Required (ErrorMessage="Please enter student name")]
        public string StudentName { get; set; }
        [Required(ErrorMessage = "Please enter Tenth percentage")]
        [Range(0 ,10)]
        public int TenthPercentage { get; set; }
        [Required(ErrorMessage = "Please enter Plus2 percentage")]
        [Range(0, 100)]
        public int Plus2Percentage { get; set; }
        [Required(ErrorMessage = "Please enter Entrance rank")]
        [Range(1, 10000)]
        public int EngineeringEntranceRank { get; set; }
        public bool HavingYearGap { get; set; }
    }
}

     In above we are using Required parameter,so our MVC application will throw required message for Student Name filed when nothing entered and submitting data.Similarly for remaining fields too.
And one more validations like Range is used to allow the numbers between the specified range only.If we are going to give wrong data and submit details we get error message.

    For this validations just change Course controller code in Post method of Index Action  like below.


[HttpPost]
        public ActionResult Index(Student objstudent)
        {
            if (ModelState.IsValid)
            {

                if (objstudent.HavingYearGap != false)
                {
                    if (objstudent.TenthPercentage > 70 && objstudent.Plus2Percentage > 70 && objstudent.EngineeringEntranceRank < 4000)
                    {
                        ViewBag.Student = "Hi" + objstudent.StudentName + ",You got selected";
                    }
                    else
                    {
                        ViewBag.Student = "Sorry" + objstudent.StudentName + ",You not selected";
                    }
                }
                else
                {
                    ViewBag.Student = "Sorry" + objstudent.StudentName + ",Year gaps not acceptable";
                }
                return View("Result");
            }
            else
            {
                return View();
            }
        }

      Here we used ModelState.IsValid in our controller for validation problems.If there is any validation errors it will return false.

     For displaying errors in view we are going to add @Html.ValidationSummary() helper method inside Html.BeginForm() helper method like below.

@{
    Layout = null;
}

<!DOCTYPE html&gt

<html&gt
<head&gt
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.ValidationSummary()
            <p>Student Name: @Html.TextBoxFor(x => x.StudentName) </p>
            <p>Tenth Percentage: @Html.TextBoxFor(x => x.TenthPercentage)</p>
            <p>10+2 Percentage: @Html.TextBoxFor(x => x.Plus2Percentage)</p>
            <p>Engg. Entrance Rank: @Html.TextBoxFor(x => x.EngineeringEntranceRank)</p>
            <p>
                Having Year Gap?
                @Html.DropDownListFor(x => x.HavingYearGap, new[] {
                                new SelectListItem() {Text = "Yes",Value = bool.FalseString},
                                new SelectListItem() {Text = "No",Value = bool.TrueString}
                                      })
            </p>
            <input type="submit" value="Submit Details" />
        }
    </div>
</body>
</html>

     Now run the application and submit the details with empty fileds.Then we will came across following error messages shown below.

Model Validations

      Try different scenarios and check the validation messages. Second ,Third and fourth fields accepts only (0 to 100),(0 to 100) and (1 to 10000) values respectively.