Monday, December 2, 2019

Angularjs in Asp.net MVC

Angularjs:

  • Angularjs means it is a javascript framework which is use for developing a single page application.
  • Single page application nothing but where on a single page we are going to render total application in one page where all your data going to be display.
  • It is a client-side script.
  • It is supported by Google company.
  • It is developed by Hevery.
  • Angularjs is running faster than mvc application.
  • If you create mvc project we have context page, index page and AboutUs pages are there. But in angularjs we have single page
  • We are going to replays your data into be a view and we are not going to be instance and we are not going to be create object in a particular server, newly created pages all other things.
  • Angularjs is bring for us 5 times faster than MVC application.
  • Angularjs is separate from mvc in one case
  • Where is not going to create multiple pages, it’s going to have one page only.
  • In what our have view, controller and model it’s going to take it or render it on a single page.
  • The base will be there one the base some like content or things will be change.
  • For example, we take some teachers in your collage, the teachers go and take class for students. After one year later freshers is came the same teacher go and take a class for freshers.
  • Angularjs is flow of mvc architecture
  • Angularjs is used to develop webapplication and mobile application.
  • Angularjs developed by google employee he names was Hevery.
  • He stated he’s work 2012 onwards.
  • We are using 2017 onwards.
  • Angularjs have some basics
  • It is totally around the pill around of directory
  • Directory is noting but where we have some predefined code so, we need to use of predefine code to develop the angular applications.
  • We will find models, controllers, views, filters, http object, validations, form objects like lot of things we find in angularjs.
  • What will find normal programming languages all things we will find in angularjs but it’s new cover.
  • Angularjs is a javascript framework and it can be depending on your directories.
  • In Angularjs with extend the html attributes.
  • We are going to bind and write expression.
Create new project
Right click on Solution -> Add -> new project -> asp.net web application (.net Framework) -> Next -> project name (AngularExample) -> Create -> web Api and uncheck the Configure for HTTPS under the Advanced -> create, like below.



Go to the google search and type like angularjs.io.org and download the angular.min.js file. After downloaded the angular.min.js file add in Script folder in your application like below.





Then go to controller add one action method and view for particular action method.

If you want to work with angularjs we need angular.min.js library only, no need any other things.

The basic thing in angularjs is expression.

The expression we take it in two flower brackets ({{ }}) like below: 

Expression in angular
{{6+6}}

In case you don’t take angularjs library the output show like below:
{{6+6}}

Incase u take angularjs library like below:

@{
    ViewBag.Title = "Angularjs";
}
<script src="~/Scripts/angular.min.js"></script>
<h2>Angularjs</h2>
    {{6+6}}

It’s show output like below:

{{6+6}}

You adding library but expression is not working because there is one criteria when we need to start expression like, we can’t say in total page where will start the angularjs should be started. We need to be told them using ng-app.

Ng-app is nothing but directory where we start the angular application.

Angularjs lets you extend Html with new attributes called Directives.

<div ng-app="">

</div>

@{
    ViewBag.Title = "Angularjs";
}
<script src="~/Scripts/angular.min.js"></script>
<h2>Angularjs</h2>
<div ng-app="">
    {{6+6}}
</div>

When you build the application, the output is show 12.

Incase you write the expression above the div tag it’s not going to be work.

Basically, Angularjs fallows model view controller type approach like mvc arch.

You Add a folder like Angular in this project 

in that folder add like FirstApplication.js file. FirstApplication.js file is a controller in Angularjs.

The controller coming so, that controller is not going to coming for you on basics of C# class in Angularjs. That's going to indicate like javascript file. It's not going to indicate any other file.

In Angularjs have so many directories are there like ng-app, ng-init, ng-model, ng-bind 

All the directories going to define inside the html only, Like below
<div ng-app="">
    {{6+6}}
    <input type="text" ng-model="FirstName" />
</div>
In above example type is a one type of attribute and ng-model also one type of attribute.

Anything which is inside the controller is called as attribute.

ng-app: directive also tells Angularjs that the <div> element is the “Owner” of the Angularjs application.

ng-app is starting of the Angularjs file.

Data Binding in Angularjs binds Angularjs expression with Angularjs data.

How to bind the string or values like below:

<div ng-app="">
    <input type="text" ng-model="FirstName" />
    {{FirstName}}
</div>

Input tag type is text so, the string will be store in ng-model variable.

ng-model: it's bind the data of your controlles.

ng-init: is a initializes of things.

how can we bind the data in Angularjs?

two ways 
1.Expression
2.ng-bind

ng-bind: 

   when we take apart from controls like below
         <p ng-bind="FirstName"></p>

it's not similar like ng-model but, ng-model is store the data in FirstName variable then bind the data in Expression way like {{FirstName}} but, ng-bind its store the data directly no need to write expression.

Curd operation in Angularjs
Controller: This is a regular javascript object which is used to control the data of the AngularJS application.
Scope: It is the Binding part between the view and the controller. It is an object with defined properties and methods.
Right click on the Angular folder -> Add -> JavaScript File -> Name (FirstApplication)-> Ok


Then javascript file will be created.Copy below code in FirstApplication.js file
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
    $http.get("http://localhost:51155/api/EmployeeModels")
        .then(function (response) {
            alert(response.data);
            $scope.EmployeeData = response.data;
        })
When you create a curd operation in angular first we define variable like var app
Create an angular module and specify a name to it
var app = angular.module('myApp', []);
 here my model name is myApp & my application name also myApp
second parameter [] means we can inherit services for our application
 create controller name
app.controller('myCtrl', function ($scope, $http){});

 Scope is nothing but through which we are going to pass some data from controller to view and view to controller.
$scope is passing the data from controller to view & view to controller.
It’s a two-way communication.
$http is another service to injected to the controller, I want to use get method post method, all http verbs we want to use it.

$http.get("http://localhost:51155/api/EmployeeModels")

.then(function (response) {

Above function is used to check the condition for data getting or not
Incase the data is getting or not give alert and check it like bellow.
alert(response.data);
then store the data in $scope.EmployeeData, then $scope.EmployeeData send data to view page using help of $scope. Like below
$scope.EmployeeData = response.data;

In view page (AngularExample.cshtml) you the below code
<div ng-app="myApp" ng-controller="myCtrl">
    <table class="table-bordered">
        <tr>
            <th>DeptId</th>
            <th>EmpId</th>
            <th>EmpName</th>
            <th>EmpSalary</th>
        </tr>
        <tr ng-repeat="x in EmployeeData">
            <td>{{x.DeptId}}</td>
            <td>{{x.EmpId}}</td>
            <td>{{x.EmpName}}</td>
            <td>{{x.EmpSalary}}</td>
        </tr>
    </table>
</div>
In above code ng-app="myApp" in this “myApp” is Application name and ng-controller="myCtrl" in this “myCtrl” is a Controller name we defined both in FirstApplication.js page
        <tr ng-repeat="x in EmployeeData">
In above code EmployeeData is define in controller (FirstApplication.js) page like “$scope.EmployeeData” but in view page we use only “EmployeeData”.
ng-repeat: It is one of the directories, it’s works like a foreach loop
 it is a directive to repeats an HTML element.

Which directory we are going to use to repeat in Angularjs? Or how to loop in Angularjs?
ng-repeat

if you want access from FirstApplicaion.js in your view (AngularExample.cs) page, first add the script file in view like below
<script src="~/Angular/FirstApplication.js"></script> 


for inserting purpose copy below code in FirstApplication.js page
    $scope.save = function () {
        $http({
            method: "POST",
            url: "http://localhost:51155/api/EmployeeModels1",
            data: {
                DeptId: $scope.DeptId,
                EmpName: $scope.EmpName,
                EmpSalary: $scope.EmpSalary
            }
        }).then(function mySuccess(response) {
            alert('Inserted Successfully');
        }),function myError(response) {
            alert('Not Inserted');
        }
    }
Copy below code in AngularExample.cs page
    <form>
        <label>DeptId</label>
        <input type="text" ng-model="DeptId" /><br />
        <label>EmpName</label>
        <input type="text" ng-model="EmpName" /><br />
        <label>EmpSalary</label>
        <input type="text" ng-model="EmpSalary" /><br />
        <input type="button" value="Save" ng-click="Save()" />
    </form>
Copy above inside <div> tag.
ng-Click: it is one of the directories, it is a click event




Tuesday, November 26, 2019

Web API in ASP.net MVC

Web API


Web API is a platform for building Restful Services. 

Rest - Representational state transfer

Rest is a simple way of sending and receiving data between client and server and it doesn't have very many standards defined. You can send and receive data as JSON, XML or even plain text. Its light weighted compared to SOAP.

Web API supports different formats of response data. Built-in support for JSON, XML format.
Restful service is nothing but design pattern.
Url based application developed by Web APi only
Web api give the URl based on url when hit the Url to get the response. That particular response access by PHP, .NET, JAVA any other technology or any other application access by it. 
Web api have a structure in the form of mvc (Model View Controller).
In our web Api will not have any concept of views, we have a model & controller, but views are nothing but url what your going to get it.
In WEB API Controllers do not return views, only part of Model and Controller.  
WEB API Controller: 
The following is a simple controller class added by visual studio by default when we created a new Web API project in the Create WEB API Project section. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Asp.net_WebApi.Controllers
{
    public class ValuesController : ApiController
   {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {

        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
} 
As you can see in the above example, ValuesController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete 
Whenever you create web api methods by using prefix of HTTP verbs. 
Difference between ApiController and Controller

  • Web ApiController is Derives from System.Web.Http.ApiController class
      Ex : public class ValuesController : ApiController
      {
      }
  • MVC Controller is Derives from System.Web.Mvc.Controller class.
       Ex: public class EmployeeController : Controller  
      {
      }
  • Web Api Controller return data
  • MVC Controller return View 
  • Web Api Controller Method name must start with Http verbs otherwise apply http verbs attribute.
  • MVC Controller Must apply appropriate Http verbs attribute like HttpGet, HttpPost 
How to access web api controller in asp.net mvc project 
Go through ur project (Asp.net WebApi) -> App_Start -> WebApiConfig.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http; 
namespace Asp.net_WebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
We can access through api/Controller
We can’t deal with action method directly. 
When u build the web api application it shows like below:


The above page comes from home control -> index.cshtml page it’s shows  
<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>ASP.NET Web API is a framework that makes it easy to build HTTP services that reach
        a broad range of clients, including browsers and mobile devices. ASP.NET Web API
        is an ideal platform for building RESTful applications on the .NET Framework.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301870">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301871">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301872">Learn more &raquo;</a></p>
    </div>
</div>

How to get API link in above output screen
Go through ur project like Asp.net WebApi -> Areas -> Controllers -> HelpController.cs page

using System;
using System.Web.Http;
using System.Web.Mvc;
using Asp.net_WebApi.Areas.HelpPage.ModelDescriptions;
using Asp.net_WebApi.Areas.HelpPage.Models;

namespace Asp.net_WebApi.Areas.HelpPage.Controllers
{
    /// <summary>
    /// The controller that will handle requests for the help page.
    /// </summary>
    public class HelpController : Controller
    {
        private const string ErrorViewName = "Error";

        public HelpController()
            : this(GlobalConfiguration.Configuration)
        {
        }

        public HelpController(HttpConfiguration config)
        {
            Configuration = config;
        }

        public HttpConfiguration Configuration { get; private set; }

        public ActionResult Index()
        {
            ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
        }

        public ActionResult Api(string apiId)
        {
            if (!String.IsNullOrEmpty(apiId))
            {
                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
                if (apiModel != null)
                {
                    return View(apiModel);
                }
            }

            return View(ErrorViewName);
        }

        public ActionResult ResourceModel(string modelName)
        {
            if (!String.IsNullOrEmpty(modelName))
            {
                ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
                ModelDescription modelDescription;
                if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
                {
                    return View(modelDescription);
                }
            }

            return View(ErrorViewName);
        }
    }
}

This page will generate links for us like below 
Note: Don't Change above code. 


If changed method name in ValuesController.cs page like below
       // GET api/values
        public IEnumerable<string> AGet()
        {
            return new string[] { "value1", "value2" };
        }
Now run the application the output show like below

In above output screen Get and Post Method are not visible in value section, because we add A before GET method. So, don’t write before GET method. The methods start with HTTP Verbs only (Get, Post, Put, Delete).
If you want to change method name u can add after Http Verbs like GetA.
       // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
How many Get methods we can define in Web Api controller?

According to user requirement we can define no of get method in web api controller. The controller is a class so, in class we define no.of methods.

But, we can define same type of method without parameter in ValueController.cs page like below
        // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
       // GET api/values
        public IEnumerable<string> GetB()
        {
            return new string[] { "B1", "B2" };
        }

In above output Value section, we miss Get methods, if you want those method we can use route concept.

Web API Routing:

Web API routing is similar to ASP.NET Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.

Web API supports two types of routing:
1. Attribute Routing
2. Convention-based Routing
Attribute Routing:
Place on a controller or action to expose it directly via a route. 

When u have same methods and same parameter in that time we use attribute base routing.

If you want to get through method you define Route like below
  // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
       // GET api/values
        [Route("GetEmployee")]
        public IEnumerable<string> GetB()
        {
            return new string[] { "B1", "B2" };
        }

When you see two square bracket ([]) are there inside u write anything that is called as attribute.



the above output it's add two more Get methods because u add 
[Route("GetEmployee")]

that means we define two different method name and same Patten in that time we can use route method.

when u call GetEmployee (https://localhost:44387/GetEmployee)  it will display output like below:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>B1</string>
<string>B2</string>
</ArrayOfstring>

I get B1 and B2 string

Now I define one more method in ValueController.cs page like below: 
        // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
        [Route("GetEmployee")]
        public IEnumerable<string> GetB()
        {
            return new string[] { "B1", "B2" };
        }
        [Route("GetEmployeeInfo")]
        public IEnumerable<string> Getc()
        {
            return new string[] { "B1", "B2" };
        }
 when you build the application it's show like below
 Incase if you want to define URL base, you define like below in your ValueController.cs page. 
        // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
        [Route("api/Values/GetEmployee")]
        public IEnumerable<string> GetB()
        {
            return new string[] { "B1", "B2" };
        }
        [Route("api/Values/GetEmployeeInfo")]
        public IEnumerable<string> Getc()
        {
            return new string[] { "B1", "B2" };
        }
 when you build the application it's show like below


But any controller (valueController.cs page) we can define no of method. if you create static url, incase if you want to change the url we go each and every method then change. it's a time taking Processes that way RoutePrefix came into picture. 

RoutePrefix:

A controller with a route prefix that applies to all actions within the controller

It's means before attribute routing


now we can change like below in ValueController.cs page. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Asp.net_WebApi.Controllers
{
    [RoutePrefix("api/Values")]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> GetA()
        {
            return new string[] { "value1", "value2" };
        }
        [Route("GetEmployee")]
        public IEnumerable<string> GetB()
        {
            return new string[] { "B1", "B2" };
        }
        [Route("GetEmployeeInfo")]
        public IEnumerable<string> GetC()
        {
            return new string[] { "B1", "B2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        } 
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        } 
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}
The output comes like below:


Convention-based Routing:

In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.

Now we define convention based routing in ValueController.cs page like below:

public IEnumerable<string> GetD(string name, string Designation)
{
      return new string[] { "B1", "B2" };
 }

when you run the application output show like below:

When u click the EmployeeInfoDetails it will show one window like


when you pass the parameters in convention-based routing it's display the querystring.

if we don't want to display querystring, then we go for attribute based routing.