Model Binding & Validation In Asp.Net Core MVC by Sagar Jaybhay

Asp.net-core By Sagar Jaybhay

Model Binding & Validation In Asp.net Core by Sagar Jaybhay

Model Binding

If we are not using model binding then we need to write lots of code to pass that form data to the action method. But by using model binding it is easy to pass data from view to action method in the controller.

The types of data we need to pass are maybe simple types like integer, string, double or complex type like Customer, Employee, Student.

In asp.net MVC model binding is done automatically from view to controller which in turn save lots of timing.

MVC binds request data to action parameters by names of that query string and parameters name in action method.

There is an order in which MVC binds the request data to action method parameters.

  1. Form Value
  2. Route Data
  3. Query String

In MVC application we can’t have 2 same method name with only parameters are different or signature different. It will throw an error to avoid this first at least you need to use httppost or httpget attribute or by ActionName attribute to given different name.

        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
       
        [HttpPost]
        public RedirectToActionResult Create(Student student)
        {
            var st=_repository.AddStudent(student);
            return RedirectToAction("Details", new { id=st.StudentId });
        }

By using action name:-

        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
       
        [ActionName("CreateStudent")]
        [HttpPost]
        public RedirectToActionResult Create(Student student)
        {
            var st=_repository.AddStudent(student);
            return RedirectToAction("Details", new { id=st.StudentId });
        }

Model Validation:

First, our student class is our model. Which shown below.

    public class Student
    {
        public int StudentId { get; set; }
        [Required]
        public string FullName { get; set; }
        [Required]
        public string Address { get; set; }
        public Divi Division { get; set; }
    }

And this class we have fullname and address are mandetory fields means we required that data without that we not forword request. So if this data is required we use Required attribute and is present in  using System.ComponentModel.DataAnnotations; this namespace.

So this is model side code and we need to check whether our model is valid or not we need this kind of changes in our HomeController also so we code like below.

       [ActionName("CreateStudent")]
        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                var st = _repository.AddStudent(student);
                return RedirectToAction("Details", new {id = st.StudentId});
            }

            return View("Create");
        }

In this method, we first check whether the model is valid or not and return the response like if all model data is valid then we pass or redirecttoaction Details if not then same view we return.

But in view also we need to add validation span element.

<span asp-validation-for="StudentId" class="text-danger"></span>
asp_net_core_model_validation_sagar_jaybhay_1

Built-In Validation Attributes:

Regular Expression:

In our case, StudentID is numeric field and we don’t want to use character or string value for that we use regular expression decorator.

       [RegularExpression(@"^[0-9]*$")]
       public int StudentId { get; set; }
asp_net_core_model_validation_sagar_jaybhay_2

To print, all validation summary below the form then use below code

<div asp-validation-summary="All" class="text-danger"></div>

If you are using asp.net validation then for integer it automatically renders even if you don’t mark fields required or not. So if you want to avoid this or bypass this checking you need to make underlying data type of that field is nullable.

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts