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.

Friday, February 12, 2016

Learn AngularJS Step by Step– Lab 2(Events and Validations)

Contents

Learn Angularjs Step by Step – Lab 2 (Events and Validations)

Introduction

Step 6:- Creating functions and adding events

Step 7:- Adding HTML validators

Step 8:- Using $valid property of angular

Step 9:- Run the program

Step 10:- Understanding the full code till Lab 2

So what’s next in Lab 3

Introduction

In the previous Learn AngularJS Step by Step(Lab 1) series we saw a simple hello world example and while doing so we learnt the basics of Angular. Let us continue with Lab 2 of Learn AngularJs step by step series and in this Lab we will see how to create events and do validations in AngularJS.

In Lab 1 we executed 5 steps so let us continue in this Lab with step 6.

I would recommend you to go through the below 1 hour Learn Angular youtube video for better and speedy understanding.

Step 6:- Creating functions and adding events

So let us add a simple function “Fun1” to the same “Hello” class we created in Lab 1. “Fun1” function will display whatever data is entered into “txthello” variableusing alert.

function Hello($scope) {
        $scope.txthello = "";
        $scope.Fun1 = function(){
            alert($scope.txthello);
            }
        }
    }

Now if you are thinking that the above method “Fun1()” can be called by simple JavaScript then you are on a very wrong track. Instances created by Angular can only be accessed by angular events. So the below code will not work.

We need to use angular events to make call to the function. So if we want to call “Fun1” of we need to use “ng-click” of Angular.

Once done you should be able to see the click event in action as shown in the below figures.

Below is the complete source code of angular event as described in the above steps.

 

Step 7:- Adding HTML validators

Angular validations use HTML 5 validators internally. So let’s say we want to make sure that “txthello” cannot be null. So we need to apply three steps :-

  • Decorate the input type text with HTML validators. For example in the below code we have applied “required” attribute. There are lots of other validators in HTML 5 as well , I would suggest you go through the complete list from this article. In this article we will just use “required” for now.
  • The input text which has validators has to be enclosed in a form tag which has to named and also the textbox has to be named. For example we have named the form as “frm1” and textbox as “texthello”. Please note ID does not matter for Angular validation it should have names.
  • Now HTML validators are processed by the browsers automatically.When the end users hit submit button they would get errors in the following way in chrome. Now we do not want to use the chrome or IE validation display messages but we want angular to take control.

Below is the code which has the above three steps applied.

Step 8:- Using $valid property of angular

So now we are all set. We have the HTML validators in place. We would like to achieve two things when the end user types data in the input fields:-

  • Disable and enable button if there are validation issues.
  • Show/Hide error message of the “DIV” tag.

For that we need to use “ng-disabled” and “ng-show” directives of Angular. When any validation fire “$valid” property of angular is evaluated and set to true and false depending on data.Using this property we can enable/disable and show/hide HTML elements.

See the below code where we have set “$valid” to the button for enabling and disabling and to hide/show the “DIV” tag we have used “ng-show”.

Also very closely observe we have negated (“!”) the results.

Step 9:- Run the program

Once all things are done, press control + f5 and enjoy your hardwork. Below is an animated GIF which shows how the program looks like when it’s running.

Step 10:- Understanding the full code till Lab 2

Below is the full code till Lab 2 with basics , events and validation.

So what’s next in Lab 3

In the next lab 3 of Learn AngularJS step by step we will see how to post Angular data to WebAPI.

Sunday, February 7, 2016

Learn Angularjs Step by Step– Lab 1

Contents

Learn AngularJS Step by Step – Lab 1

Introduction

Step 1:- Creating a simple HTML hello world project

Step 2:- Get AngularJS framework

Step 3:- Applying ng-controller ,ng-model and expressions

Step 4:- ng-app and understanding scoping

Step 5:Bootstrapping the project and seeing the results

Final Complete code

What in Next Lab ?

Introduction

AngularJS is one the most talked JavaScript framework. Rich bindings of Angular make HTML and Javascript object interaction like a breeze. The core reason why Angular was born was binding, binding and binding. It’s a binding framework it binds the HTML UI with Javascript objects.

By doing so it reduces lot of interaction code we need to write between HTML and Javascript objects.

For the same reason Angular team also named it as a MVW framework. Where “M” stands for javascript objects , “V” stands for HTML UI and “W” stands Whatever code that binds the model and UI. Lot of people call this whatever code as gel code , behind code , view model and so on.

To understand Angular MVW framework concept I would suggest you to see the below 1 hour youtube video which explains the concept in more detail.

So in this demo we will create simple UI

Step 1:- Creating a simple HTML hello world project

So let us go ahead and create a simple project and get angular in it. Now when we create any project in visual studio it always has that Microsoft stamp attached to it.

I mean for example when you create an empty ASP.NET Web application you would get“Web.config” files , ASPX files etc. These files are very much Microsoft specific.

Now to maintain the purity of angular we would like create a simple project which does not have Microsoft stamp on it. But at the same time we would like to get the benefits of visual studio intellisense.

This would be a simple project with just HTML , CSS , JS files and Angular files. So create a simple folder in your hard drive and open visual studio and click fileàopenàWebsite as show in the below figure. When you open a folder as website , visual studio does not add unnecessary files like web.config and global.asax files etc.

And give the path of the folder as shown in the below figure.

Once you have done you would see a very simple project which does not have anything. It just has a simple project with no Microsoft specific files.

In this project let us add a simple HTML page and name it as “HelloWorld.html”.

 

In thisHTML page we will create a simple input text box called as “txtHello” and this text box will bind with “Hello” javascript function / class.

You can see the below code where we have the hello world text box and the javascript function “Hello” and our goal is to bind the text box with the javascript function.

And now we would be using Angular to bind these two entities.

Step 2:- Get AngularJS framework

Now that we have the HTML UI and Javascript class in place let us first get AngularJS framework. Right click on project and click Manage NuGet Packages as shown in the below figure.

Search Angular in the search text box and install “AngularJS” core from the list. You can see lot of other Angular packages those are extensions of Angular. We will see the other packages later on gradually.
The most important is Angular core so click on install and get it.

At the Time of installation the below dialog box will be appear (select project) click ok.

Once installed you can see the Angular files in the scripts folder.

Now reference the “Angular” file using the script tag as show in the below code( see the bold lines).

Step 3:- Applying ng-controller ,ng-model and expressions

Now in order to bind the “HelloWorld” class with hello HTML text box we need to do two things :-

  • Create an instance of “HelloWorld” class.
  • Second set the property of the “HelloWorld” object to the textbox.

For this we need to use “ng-controller” and “ng-model”. “ng-controller” and “ng-model” are termed as directives. Remember angular is a declarative programming language.

Declarative means you just apply the directive and things will work. In case you are new to this declarative work I would suggest you to quickly see the below video link where its explained with a example https://youtu.be/0kmdjqgO9IY?t=15m33s

“ng-controller” directive creates an object of “Helloworld” controller and binds it with the UI DIV tag and “ng-model” binds the property with textbox with “txtHello” property.

To display the property on the screen we need to expression “{{}}” as shown in the below code. So when we type in the text “txthello” it will get displayed inside the “div1” tag.

Step 4:- ng-app and understanding scoping

So if “ng-controller” directive creates instances , what will happen if you have multiple “ng-controller” directives in your HTML page as shown in the below code. Will it create two instances or one instance ?.

Think about it….

Obviously as a developer you would like different instances of “HelloWorld” to bind with both the DIV HTML UI. That’s what exactly AngularJS does he creates two different instances.

But now if there are two instances in the same HTML page what is the scope of these two instances , is it full HTML page or something else ?.

The scope of these two instances is the start of the tag "<div> and end of '' </div> tag. These instances are created by angular automatically when angular encounters “ng-controller” tag.

Now there can be a situation where want these controller instances to communicate with each other , share some common data. That’s where we have something called as “ng-app”.

“ng-app” creates a top object which has control of all controller objects and they also help to communicate shared data between the controller instances.

Step 5:Bootstrapping the project and seeing the results

So now that we are all setup we need some code which help to kick off angular. We would like angular to start creating the controller objects ,ng-app objects and do the binding.

So we need two lines of code as shown below. The first line creates the app instance and the second line adds the controller object to the app.

var myApp = angular.module("myApp", []);
myApp.controller("HelloWorld", Hello);

So that’s it , press control + f5 and see the fun of automatic binding in action. The time you type on the textbox expression are updated.

Final Complete code

Below is the complete source code for the same.

What in Next Lab ?

In the next Lab we will see how use events and validations in Angular.