{"id":580,"date":"2015-05-13T13:49:00","date_gmt":"2015-05-13T13:49:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=580"},"modified":"2025-02-25T13:42:29","modified_gmt":"2025-02-25T13:42:29","slug":"asp-net-mvc-and-entity-framework","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/asp-net-mvc-and-entity-framework","title":{"rendered":"How To Use AngularJS in ASP.NET MVC and Entity Framework"},"content":{"rendered":"\n<p>These days, it seems like\u00a0<em>everyone\u00a0<\/em>is talking about AngularJS and ASP.NET MVC. So in this post, we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC by demonstrating how to use AngularJS in an ASP.NET MVC application.<\/p>\n\n\n\n<p>Before you learn about<b> <\/b>using AngularJS in ASP.NET MVC, check out Infragistics\u2019 jQuery library,&nbsp;<a href=\"\/products\/ignite-ui\">Ignite UI for JavaScript<\/a>, which helps you write and run web applications faster. You can use the Ignite UI for JavaScript library to help quickly solve complex LOB requirements in HTML5, jQuery, Angular, React, or ASP.NET MVC. <a href=\"\/products\/ignite-ui\/download\">Download a free trial of Ignite UI<\/a> today.<\/p>\n\n\n\n<p>To start, let\u2019s create ASP.NET MVC application and right click on the MVC project. From the context menu, click on Manage Nuget Package. Search for the AngularJS package and install into the project.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar\/3252.picture_5F00_1_5F00_d.png\" alt=\" let\u2019s create ASP.NET MVC application\" title=\"let\u2019s create ASP.NET MVC application\"\/><\/figure>\n\n\n\n<p>After successfully adding the AnngularJS library, you can find those files inside the Scripts folders.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"reference-angularjs-library\">Reference:&nbsp;AngularJS library<\/h2>\n\n\n\n<p>You have two options to add an AngularJS library reference in the project: MVC minification and bundling or by adding AngularJS in the Script section of an individual view. If you use bundling, then AngularJS will be available for the whole project. However, you have the option to use AngularJS on a particular view as well.<\/p>\n\n\n\n<p>Let\u2019s say you want to use AngularJS on a particular view (Index.cshtml) of the Home controller. First, you need to refer to the AngularJS library inside the scripts section as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@section scripts{\n    &lt;script src=\"~\/Scripts\/angular.js\">&lt;\/script>\n}<\/pre>\n\n\n\n<p>Next, apply the ng-app directive and any other required directives on the HTML element as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;div ng-app=\"\" class=\"row\">\n     &lt;input type=\"text\" ng-model=\"name\" \/>\n     {{name}}\n&lt;\/div><\/pre>\n\n\n\n<p>When you run the application you will find AngularJS is up and running in the Index view. In this approach, you will not be able to use AngularJS on the other views because the AngularJS library is only referenced in the Index view.<\/p>\n\n\n\n<p>You may have a requirement to use AngularJS in the whole MVC application. In this case, it\u2019s better to use bundling and minification of MVC and all the AngularJS libraries at the layout level. To do this, open BundleConfig.cs from the App_Start folder and add a bundle for the AngularJS library as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static void RegisterBundles(BundleCollection bundles)\n        {\n            bundles.Add(new ScriptBundle(\"~\/bundles\/angular\").Include(\"~\/Scripts\/angular.js\"));<\/pre>\n\n\n\n<p>After adding the bundle in the BundleConfig file, next you need to add the AngularJS bundle in the _Layout.cshtml as listed below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;head>\n    &lt;meta charset=\"utf-8\" \/>\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    &lt;title>@ViewBag.Title - My ASP.NET Application&lt;\/title>\n    @Styles.Render(\"~\/Content\/css\")\n    @Scripts.Render(\"~\/bundles\/modernizr\")\n    @Scripts.Render(\"~\/bundles\/angular\")\n    @Scripts.Render(\"~\/bundles\/jquery\")\n    @Scripts.Render(\"~\/bundles\/bootstrap\")\n    @RenderSection(\"scripts\", required: false)\n&lt;\/head><\/pre>\n\n\n\n<p>After creating an AngularJS bundle and referring to it in _Layout.cshtml, you should be able to use AngularJS in the entire application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"data-from-database-and-in-the-angularjs\">Data From Database and in the AngularJS<\/h2>\n\n\n\n<p>So far we have seen how to set up AngularJS at a particular view level and the entire application level. Now let\u2019s go ahead and create an end to end MVC application in which we will do the following tasks:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Fetch data from the database using the EF database first approach<\/li>\n\n\n\n<li>Return JSON from the MVC controller<\/li>\n\n\n\n<li>Create an AngularJS service to fetch data using the $http<\/li>\n\n\n\n<li>Create an AngularJS controller<\/li>\n\n\n\n<li>Create an AngularJS view on the MVC view to display data in the table<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"connect-to-a-database-using-the-ef-database-first-approach\">Connect to a Database Using the Ef Database First Approach<\/h2>\n\n\n\n<p>To connect to a database with the EF database-first approach, right click on the MVC application and select a new item. From the data tab, you need to select the option ADO.NET Entity Model as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"538\" src=\"https:\/\/staging.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image-1024x538.png\" alt=\" you need to select the option ADO.NET Entity Model\" class=\"wp-image-1587\" title=\" you need to select the option ADO.NET Entity Model\" srcset=\"https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image-1024x538.png 1024w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image-300x158.png 300w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image-768x403.png 768w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image-480x252.png 480w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2015\/05\/image.png 1095w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>From the next screen, select the \u201cEF Designer from database\u201d option.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.infragistics.com\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar\/4848.picture_5F00_3_5F00_d.png\" alt=\" select the \u201cEF Designer from database\u201d\" title=\"select the \u201cEF Designer from database\u201d\"\/><\/figure>\n\n\n\n<p>On the next screen, click on the New Connection option. To create a new connection to the database:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Provide the database server name<\/li>\n\n\n\n<li>Choose the database from the drop-down. Here we are working with the \u201cSchool\u201d database, so we\u2019ve selected that from the drop-down.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.infragistics.com\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar\/3750.picture_5F00_4_5F00_d.png\" alt=\" Choose the database from the drop-down.\" title=\"Choose the database from the drop-down.\"\/><\/figure>\n\n\n\n<p>On the next screen, leave the default name of the connection string and click next.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.infragistics.com\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar\/3652.picture_5F00_5_5F00_d.png\" alt=\" the next screen, leave the default name of the connection string\" title=\"the next screen, leave the default name of the connection string\"\/><\/figure>\n\n\n\n<p>On the next screen, select the tables and other entities you want to keep as the part of the model. To keep it simple I am using only the \u201cPerson\u201d table in the model.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.infragistics.com\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar\/7457.picture_5F00_6_5F00_d.png\" alt=\" select the tables and other entities you want to keep as the part of the model\" title=\"select the tables and other entities you want to keep as the part of the model\"\/><\/figure>\n\n\n\n<p>As of now, we have created the connection with the database and a model has been added to the project. You should see an edmx file has been added as part of the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"return-json-from-the-mvc-controller\">Return Json From the Mvc Controller<\/h2>\n\n\n\n<p>To return the Person data as JSON, let us go ahead and add an action in the controller with the return type JsonResult. Keep in mind that you can easily write a Web API to return JSON data; however the purpose of this post is to show you how to work with AngularJS, so I\u2019ll stick with the simplest option, which is creating an action which returns JSON data:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public JsonResult GetPesrons() {\n    SchoolEntities e = new SchoolEntities();\n    var result = e.People.ToList();\n    return Json(result, JsonRequestBehavior.AllowGet);\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"create-an-angularjs-service-to-fetch-data-using-the-http\">Create an AngularJS Service To Fetch Data Using the $HTTP<\/h2>\n\n\n\n<p>Here I assume that you already have some knowledge about these AngularJS terms, but here\u2019s a quick review\/intro of the key concepts:<\/p>\n\n\n\n<p><strong>Controller<\/strong><\/p>\n\n\n\n<p>A controller is the JavaScript constructor function which contains data and business logic. The controller and the view talk to each other using the $scope object. Each time a controller is used on the view, an instance gets created. So if we use it 10 times, 10 instances of the constructor will get created.&nbsp;<\/p>\n\n\n\n<p><strong>Service<\/strong><\/p>\n\n\n\n<p>A service is the JavaScript function by which an instance gets created once per application lifecycle. Anything shared across the controller should be part of the service. A service can be created in five different ways. The most popular way is by using the service method or the factory method. AngularJS provides many built-in services also: for example, the $http service can be used to call an HTTP based service from an Angular app, but a service must be injected before it is used.<\/p>\n\n\n\n<p><strong>Modules<\/strong><\/p>\n\n\n\n<p>Modules are the JavaScript functions which contain other functions like a service or a controller. There should be at least one module per Angular app.<\/p>\n\n\n\n<p>Note: These are the simplest definitions of these AngularJS concepts. You can find more in-depth information&nbsp;on the web.<\/p>\n\n\n\n<p>Now let\u2019s start creating the module! First, right-click on the project and add a JavaScript file. You can call it anything you\u2019d like, but in this example, let\u2019s call it StudentClient.js.<\/p>\n\n\n\n<p>In the StudentClient.js we have created a module and a simple controller. Later we will modify the controller to fetch the data from the MVC action.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var StudentApp = angular.module(\"StudentApp\", []);\n\nStudentApp.controller(\"StudentController\", function ($scope) {\n    $scope.message = \"Infrgistics\";\n});<\/pre>\n\n\n\n<p>To use the module and the controller on the view first, you need to add the reference to the StudentClient.js and then set the value of ng-app directive to the module name StudentApp. Here\u2019s how you do that:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@section scripts{\n     &lt;script src=\"~\/StudentClient.js\">&lt;\/script>\n}\n&lt;div ng-app=\"StudentApp\" class=\"row\">\n    &lt;div ng-controller=\"StudentController\">\n        {{message}}\n    &lt;\/div>\n&lt;\/div><\/pre>\n\n\n\n<p>At this point, if you run the application, you will find Infragistics rendered on the view. Let\u2019s start with creating the service. We will create the custom service using the factory method. In the service, using the $http in-built service will call the action method of the controller.&nbsp;&nbsp;Here we\u2019re putting the service in the same StudentService.js file.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">StudentApp.factory(\"StudentService\", [\n    \"$http\",\n    function ($http) {\n        var StudentService = {};\n\n        StudentService.getStudents = function () {\n            return $http.get(\"\/Home\/GetPersons\");\n        };\n\n        return StudentService;\n    },\n]);\n<\/pre>\n\n\n\n<p>Once the service is created, next you need to create the controller. In the controller, we will use the custom service and assign returned data to the $scope object. Let\u2019s see how to create the controller in the code below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">StudentApp.controller(\"StudentController\", function ($scope, StudentService) {\n    getStudents();\n    function getStudents() {\n        StudentService.getStudents()\n            .success(function (studs) {\n                $scope.students = studs;\n                console.log($scope.students);\n            })\n            .error(function (error) {\n                $scope.status =\n                    \"Unable to load customer data: \" + error.message;\n                console.log($scope.status);\n            });\n    }\n});\n<\/pre>\n\n\n\n<p>Here we\u2019ve created the controller, service, and module. Putting everything together, the StudentClient.js file should look like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var StudentApp = angular.module(\"StudentApp\", []);\nStudentApp.controller(\"StudentController\", function ($scope, StudentService) {\n    getStudents();\n    function getStudents() {\n        StudentService.getStudents()\n            .success(function (studs) {\n                $scope.students = studs;\n                console.log($scope.students);\n            })\n            .error(function (error) {\n                $scope.status =\n                    \"Unable to load customer data: \" + error.message;\n                console.log($scope.status);\n            });\n    }\n});\n\nStudentApp.factory(\"StudentService\", [\n    \"$http\",\n    function ($http) {\n        var StudentService = {};\n\n        StudentService.getStudents = function () {\n            return $http.get(\"\/Home\/GetPersons\");\n        };\n\n        return StudentService;\n    },\n]);\n<\/pre>\n\n\n\n<p>On the view, we can use the controller as shown below, but keep in mind that we are creating an AngularJS view on the Index.cshtml. The view can be created as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@section scripts{\n    &lt;script src=\"~\/StudentClient.js\">&lt;\/script>\n}\n\n&lt;div ng-app=\"StudentApp\" class=\"container\">\n    &lt;br\/>\n    &lt;br\/>\n    &lt;input type=\"text\" placeholder=\"Search Student\" ng-model=\"searchStudent\" \/>\n    &lt;br \/>\n    &lt;div ng-controller=\"StudentController\">\n        &lt;table class=\"table\">\n            &lt;tr ng-repeat=\"r in students | filter : searchStudent\">\n                &lt;td>{{r.PersonID}}&lt;\/td>\n                &lt;td>{{r.FirstName}}&lt;\/td>\n                &lt;td>{{r.LastName}}&lt;\/td>\n            &lt;\/tr>\n        &lt;\/table>\n    &lt;\/div>\n&lt;\/div>\n<\/pre>\n\n\n\n<p>On the view, we are using ng-app, ng-controller, ng-repeat, and ng-model directives, along with \u201cfilter\u201d to filter the table on the input entered in the textbox. Essentially these are the steps required to work with AngularJS in ASP.NET MVC application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>In this post, we focused on a few simple but important steps to work with AngularJS and ASP.NET MVC together. We also touched upon the basic definitions of some key AngularJS components, the EF database-first approach, and MVC. In further posts, we will go into more depth on these topics, but I hope this post will help you in getting started with AngularJS in ASP.NET MVC.<\/p>\n\n\n\n<p>Also, do not forget to check out&nbsp;<a href=\"https:\/\/www.infragistics.com\/products\/ignite-ui\" rel=\"noreferrer noopener\" target=\"_blank\">Ignite UI for JavaScript<\/a>, which you can use&nbsp;with HTML5, Angular, React, and ASP.NET MVC to create rich Internet applications. You can&nbsp;<a href=\"https:\/\/www.infragistics.com\/products\/ignite-ui\/download\">download a trial<\/a>&nbsp;of all our JavaScript controls for free.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/download.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-JavaScript\/Blog-incontent-IgniteUI-650x200.jpg\" alt=\" \"\/><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>These days, it seems like\u00a0everyone\u00a0is talking about AngularJS and ASP.NET MVC. So in this post, we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC by demonstrating how to use AngularJS in an ASP.NET MVC application.<\/p>\n","protected":false},"author":65,"featured_media":997,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-580","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-how-to"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/580","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=580"}],"version-history":[{"count":5,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/580\/revisions"}],"predecessor-version":[{"id":2036,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/580\/revisions\/2036"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/997"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=580"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=580"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=580"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}