Saturday, May 21, 2016

Create first application with angularJs in asp.net mvc

In this article I am going to explain how to create a first application with AngularJs in asp.net MVC.
Create first application with angularJs in asp.net mvc


Description:
In this example I am going to show a message, message is “First Application using AngularJs in MVC”.

Implementation:
To create this application follow the given steps:

Create MVC Project
Add new MVC project. I have set up an empty MVC project.

Add Controller
Now add an empty controller (Angular Controller) to project.
Controller looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_Project.Controllers
{
    public class AngularController : Controller
    {
        //
        // GET: /Angular/
        public ActionResult Index()
        {
            return View();
        }
    }
}

Add view
Now right click on Index and add view.

Add AngularJs to Project
You have two options to add the angulatJs in project.
1st you can add the AngularJs library CDN
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
2nd download the AngularJs library from its website. Copy the downloaded file and put it in your JS/Scripts folder.

<script src="~/Scripts/angular.min.js"></script>

Show message
Write the below given code to show message on index.
<script>
    message();
    function message () {
        var app = angular.module('mvcapp', []);
        app.controller('AngularController', function ($scope) {
        $scope.Message = "First Application using AngularJs in MVC";
        });
    }
</script>

Complete code of View (index.cshtml):
@{
    ViewBag.Title = "MVC-AngualatJs Application";
}

<h2>MVC-AngualatJs Application </h2>

<div ng-app="mvcapp" ng-controller="AngularController" class="row">
    {{Message}}
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script>
    message();
    function message () {
        var app = angular.module('mvcapp', []);
        app.controller('AngularController', function ($scope) {
        $scope.Message = "First Application using AngularJs in MVC";
        });
    }
</script>

  



No comments:

Post a Comment