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)

Saturday, February 27, 2016

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

Contents

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

Introduction

Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate

Step 2: Creating project

Step 3: Add a New Controller

Step 4: Add a view

Step 5: Putting code in the controller and view

Step 6: Run the project

Step 7: Creating the student model

Step 8: Adding the students controller

Step 9: Creating the students screen

Step 10: Writing logic for Submit click

Step 11: Run the application

Introduction

This article series is targeted for freshers who want to learn ASP.NET MVC. So if you are senior then I would suggest to start from this MVC article.

So in this two partarticle I will be creating a simple student data entry screen using ASP.NET MVC , ADO.NET and Jquery. I have used the below youtube video for reference purpose. And would encourage any new ASP.NET MVC learner to first see this videoto get a good kick start.

I have broken this tutorial in to two parts. In part 1 we will see what we need to start MVC , we will learn the basics of creating controller , models and view and then we would create a simple student data entry screen and see how it works with the HTTP Post and submit.

In the next article we will learn validations both client side and server side and also we will looking to how to interact with SQL Server using ADO.NET.

Step 1: Download & Install Microsoft Visual Studio 2013 Ultimate

For doing ASP.NET MVC the first thing we need is visual studio. So go ahead and install visual studio from the below link.

http://www.microsoft.com/en-US/download/details.aspx?id=44915

Step 2: Creating project

Visual studio is an official IDE for doing any kind of Microsoft development work. And to do any Microsoft development we need to create a project. So click on file – menu and project as shown in the below figure.

As said previously visual studio is used to do any kind of development like Windows, mobile , web and so on. So when we say ASP.NET MVC it is for web application. So select Visual C# à Web à ASP.Net Web Application àEnter File NameàPress ok as shown in the below figure.

Now remember ASP.NET is the main framework on which MVC, WebAPI , Webforms and other web programming technologies work. So once you create the project you will get lot of options, select MVC from the same as shown below.

Also change Authentication to “No Authentication” for now. We will learn more about authentication and authorization later. Lets first get our simple hello world project running and keep complicated things later.

Once you click ok you should see the MVC project created with all necessary files as shown below. Do not get too much confused about the folder and file structure for now. For now concentrate on only three folders “Controller”, “View” and “Model”.

Step 3: Add a New Controller

In MVC architecture the first hits comes to controller, which in turn loads the model data and this model data is then sent to the view. So the first step is to create the controller. If you see the solution there is a controller folder. So let us add a new controller by click on the Controllers folderà Add àController.

The next thing you will see is lot of readymade controller templates. But because we are learning let’s not use any readymade templates let’s start from scratch and select MVC 5 controller empty.

Now when we add a controller, do not delete the word controller from the file name. For example if you want to create a “Home” controller then the full name of the file is “HomeController”. The word “Controller” should be present.

4.3: Enter the Name Of Controller as Home.

Step 4: Add a view

So now that we have added controller, lets add view. To add view go to views folder and add view as shown below.

Give a proper view name and uncheck the “user layout page” box.

Finally you should see controller and views added in the respective folder as shown below.

Step 5: Putting code in the controller and view

So let’s start putting some code in Hompage.cshtml (HomePage View). In the HomePage.cshtml we have put a simple hello world text.

In the controller let’s add a simple “ActionResult” method called as “GotoHome” and in that we are returning the view.

namespaceHelloWorld.Controllers
{
publicclassHomeController : Controller
    {
//
// GET: /Home/
publicActionResult Index()
        {
return View();
        }
publicActionResultGotoHome()
        {
return View("HomePage");
        }sp;      }
	}
}

Step 6: Run the project

So once you are done with the previous steps just press control + f5 and run the project. It’s possible you get a below error as shown below. Do not get discouraged. This error comes because you have not specified the controller and action name.

On the browser URL type your controller name (without the word controller) followed by action name as shown below. In our case we have “Home” controller and action name is “GotoHome” and you should be able to see the output.

Step 7: Creating the student model

Till now we have not added any model. So let us go ahead and create a simple model by the name students. A model is nothing but a class. So right on models folder and add a class as shown in the below figure.

In the model we have created four properties for the class as shown below.

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

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

    }
}

Once you write the coderebuild the solution. I again repeat do not miss this step REBUILT THE SOLUTION.

Step 8: Adding the students controller

Let’s add a students controller from where we invoke the data entry screen for the students.

In the controller do not forget to import model namespace.

Lets add an action “Enter” which will invoke the data entry screen.

Step 9: Creating the students screen

So we have completed the model and the controller let us add a view for the same. So right click on the “Enter” Action and click add view as shown in the below figure.

Lets give the view name as “EnterStudent” and uncheck the layout page box. Layout pages are like master pages in ASP.NET webforms.

In view let’s put the below code which has four textboxes for the student data and one submit button.

So now the user will enter data and click on Submit button , we need some kind of logic in the controller for handling the submit click.

Step 10: Writing logic for Submit click

To handle the submit click we need to create submit action in the student controller.

When this submit action is called the data sent from the form will be collected and displayed in a view. Let us add a new view with name “Student” to this submit action.

This view we will connect with the model namespace where we have the customer controller.

Below is the view of the student.

When the user click on submit we need to send data to the submit action. So on the form given the action name as “Submit” and method as “Post”. And also ensure that all textboxes are provided with a name as shown in the below code. For now keep name of the textbox and the class property names same.

In the submit action we will use the request object to fetch data and load the student object and this student object is sent to “Student” view which we have created.

publicActionResult Submit()
        {
Studentobj = newStudent();
obj.StudentRollNo=Request.Form["StudentRollno"];
obj.StudentName = Request.Form["StudentName"];
obj.StudentStd = Request.Form["StudentStd"];
obj.StudentDIV = Request.Form["StudentDiv"];
return View("Student",obj);
        }

In this the student view we are displaying the values by using the “Model” object as shown below.

Step 11: Run the application

So now that all the hard work is done, take a deep breath and press control + f5 and enter the URL in format of controller name/action name :- http://localhost:22144/student/Enter

Enter data in to the text boxes and press submit.

And you should see this screen.