Friday, March 11, 2016

Learn ASP.NET MVC step by step: - Part 2

Contents

Learn ASP.NET MVC step by step: - Part 2

Introduction

Step 11: Understanding Model binder

Step 12: Create model Binder Class.

Step 13: Attach the binder with the object and execute

Step 14: Implementing validation

Step 15: Check If the validations are proper

Step 16: Displaying error message

Step 17: Client side validation with Jquery

Introduction

This complete article is a guest post written by Mr. Prathamesh mestry https://www.facebook.com/prathamesh.mestry?pnref=story . If you think he is doing a good job send him a silent thanks to his FB.

In part 1 we saw http://www.codeproject.com/Articles/1081437/Learn-ASP-NET-MVC-Step-by-Step-Part basics of how to start MVC. In this session we will see model binder and validations. In validation we will do server side validations using data annotations and client side using Jquery.

In case you are completely new to MVC we would suggest you to watch this video series Learn MVC in 16 hours given in the below youtube video.

Step 11: Understanding Model binder

Model binder helps to connect the UI controls to the model objects of MVC. In the previous article our UI text box names where same as customer class names so we did not have issues. But what if you text box names are different from class names.

For example below is a customer UI which has text box names start with “txt” and class property names are without word “txt”.

You can see the below class is not in synch with UI text box names.

publicclassStudent
{
publicstringStudentRollNo{ get; set; } //Student Roll No.
publicstringStudentName{ get; set; } //Student Name.
publicstringStudentStd{ get; set; } //Student Standard.
publicstringStudentDIV { get; set; }//Student Division.
}

This is where model binder class comes to picture. Model binder class binds the UI textboxes with model.

Step 12: Create model Binder Class.

To create a model binder class the first thing we need to do is implement interface “IModelBinder”.

Right Click on ModelBinder Class  Implement Interface  Implement Interface.

In the class we need to put the binding code in “BindModel” method as shown below.

public class StudentBinder : IModelBinder
    {

public object BindModel(ControllerContextcontrollerContext, 
ModelBindingContextbindingContext)
        {
HttpContextBaseobjContext = controllerContext.HttpContext;
stringstuRoll = objContext.Request.Form["txtStudentRollno"];
stringstuName = objContext.Request.Form["txtStudentName"];
stringstuStd = objContext.Request.Form["txtStudentStd"];
stringstuDiv = objContext.Request.Form["txtStudentDiv"];
            Student obj = new Student()
            {
StudentRollNo = stuRoll,
StudentName = stuName,
StudentStd = stuDiv,
StudentDIV = stuDiv,

            };
returnobj;
        }
    }

Step 13: Attach the binder with the object and execute

Once the binding code is completed attach the binder with the object and execute to see the results.

public ActionResult Submit([ModelBinder(typeof(StudentBinder))] Student obj)
{

return View("Student",obj);

}

Step 14: Implementing validation

Now that we have the student screen and the output is displayed it’s time to put validations. So we will be applying the following validation for our student class:-

  • Student name and roll number is required.
  • Student Rollno should be alphanumeric with 7 characters with first three letter characters and last four letter numeric for example :-ABC1234, XYZ5678.

In order to implement validations we need to import “data annotation” namespace and decorate the attributes on the student properties.

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

namespaceHelloWorld.Models
{
public class Student
    {

        [Required]
        [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string StudentRollNo{ get; set; } //Student Roll No.

        [Required]
        [StringLength(10)]
public string StudentName{ get; set; } //Student Name.
public string StudentStd{ get; set; } //Student Standard.
public string StudentDIV { get; set; }//Student Divsion.
    }
}

Step 15: Check If the validations are proper

When the object is filled the final output whether the validation is passed or failed is updated to the “ModelState” object. You can see in the below code we are checking if the “ModelState” object is valid by using the “IsValid” property.

Depending on the property value its redirecting to the views.

public ActionResult Submit(Student obj)
        {
if (ModelState.IsValid)
            {
return View("Student", obj);
            }
else
            {
return View("EnterStudent");
            }
        }

Step 16: Displaying error message

To display error message we need to use Helper class as shown in the below code.

Step 17: Client side validation with Jquery

Install Jqurey validation from Nuget.

33.1 In Solution Explorer Right Click on MyApplication (HelloWorld).  Click on Manage NuGet Packages

Search jQuery Validation.  Select Microsoft jQuery Unobtrusive Validation  install

Using Helper class Create UI elements like Textboxes.

Output Screen of EnterStudent View using Html helper Class...

Validation Output 2(incorrect RollNo)