In this article I will be sharing a basic stuff which comes handy in MVC applications. The HTML helpers provided by the Razor are smart enough to understand and process the work as required.
We will be discussing in brief about the Ajax.BeginForm, which has few concepts hidden within. When we face the difficulty or the issue, we explore and resolve. Same has happened recently with me. So lets start exploring what the hidden secrets are, which actually are very few.
This can be added from the Nuget package manager directly. I find adding from the Package Manager console easy. The script goes like below:
Install-Package jQuery.Ajax.Unobtrusive
AjaxExtensions.BeginForm is a part of System.Web.Mvc.Ajax namespace under the System.Web.MVC assembly. When used in the response it writes the HTML
With an anticipation and hope, this article would be an interesting and effective somehow. This article will be covering the Asp.Net 5’s MVC6 Welcome application. a brief about the all new concepts of MVC6 and the new structure it beholds. Then we create our first Welcome application and then have a walk through of the new Azure Portal and deploy our first web application.
The above image is all that we will be covering in our article.
A perfect blend of cloud and web application is what Asp.Net 5 is intended for. Asp.Net 5 is now being called off as .NET core is what that stands out today. It is a framework with open source & cross platform for building cloud based web applications. Here Azure comes integrated to the Visual Studio applications. Web applications either can be deployed to cloud or be running on On-premise. .Net core is available on Visual Studio 2015 build. You can download the community edition of the Visual Studio which is actually free.
Community Edition Download. Give a try for sure!
.Net 5 core contains a small optimized run time environment called “CoreCLR” One more important point to note is, .Net Core is opensource and the progress can be updated on Github. They have the code exposed and the build can be tracked easily. .Net core is said to contain a set of libraries known as “CoreFx”. Below are the links to the Github. Just have a look:
Another important benefit is termed as “Portability”. What this means is, we can package and deploy the Core CLR which can in turn help you eliminate the dependency on the installed version of .Net framework. Multiple application running on different versions of CLR can be set ups well. This is the magic the team wanted to result out, which is great!
With .NET 5 and VS 2015 comes MVC6 into picture. Microsoft builds are moving faster than the world!
When I first looked at the structure of the Solution when i added a new MVC project, I was like What!!
Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and selected the correct template. These sort of questions were flickering in my mind. When ran the application it ran successfully as well. Strange!!
MVC6, the merger, the blend of three frameworks, i.e. MVC, Web API2 & Web Pages. Previous versions of MVC, while adding a new template would prompt to check whether we want Web API along with MVC. Here we select the MVC project and we get the opportunity to work with API as well.
In previous versions there were two base controller classes, separate for normal controller and also for the Api controller, i.e. ApiController
public class TestController: Controller { } public class ApiTestController ; ApiController { }
In earlier version as shown above, the controller base class were from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC6 it is only one, i.e. Microsoft.AspNet.Mvc.Controller.
In MVC6 there comes a new title termed as Tag Helpers. They make life much more simpler. How! We will get to know once we see the code snippet.
For normal web pages, as we know the HTML helpers are defined within the System.Web.WebPages.Html under System.Web.WebPages
, whereas in MVC6, it is under the System.Web.MVC assembly..
The HTML helpers which we used to use in Razor or ASPX, were quite difficult for normal HTML developers to understand (suppose designers). Now i MVC6 that has been simplifies using the Tag Helpers.
@using (Html.BeginForm()) { @Html.LabelFor(m => p.EmpName, "Employee Name:") @Html.TextBoxFor(m => p.EmpName) <input type="submit" value="Create" /> }
But in MVC6 ,
@model AzureDemoProject.Models.Employee @addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" <form method="post"> <div><label>Employee Name:</label> <input type="text" /></div> <input type="submit" value="Save" /> </form>
Now the second snippet looks more like HTML friendly and also a bit simple.
Mr. Damian Edwards, has posted the source code on Github which has examples of Tag Helpers. Please go through for better live understanding
Git Hub Tag Helpers Download and play around.
These are the latest trending front end development tools. These are quite new to me as well, but will be learning and posting articles on these as well in coming days. Stay tuned!!
Ok branding apart, lets have a brief idea on what these are.
Bower:-This is a client side item added by default to MVC6 project. If not added, then Right click on the project-> Add->New Item
->Installed(Client Side)-> Bower.json. You can find then the file is already installed. The file is inside the wwwroot->lib->bootsrap->bower.json. As you open up the file, you can find the client side tool packages added to the project and their versions. Thus, we got to know that the bower is a client side package manager which is used to add the front-end packages like bootstrap, jQuery, angular, etc.
Grunt:-In MVC6 project when we add, we can find the gulpfile.js, this is kind of an alternative to the Grunt as both perform the same kind of functions. The operations they perform is minification, cleaning, concatenation, etc. of both js & css files.
NPM:- Node Package Manager is present under the project with the name project.json. This holds the dependencies and their versions required by the web application we have set up.
"dependencies": { "EntityFramework.Commands": "7.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1", "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final", "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final", "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final", "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final", "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final", "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final", "Microsoft.Extensions.Logging": "1.0.0-rc1-final", "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final" }, "scripts": { "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ] }
As we can see in the above snippet, which is just a part of the project.json file. This is to show the default dependencies added to the project and the pre publish scripts mentioned. When we suppose add a new dependency, suppose I try and add System.Linq, it will list up the Nuget package as intellisense and then we add the version which also comes under the intellisense. Like below image:
Then after hitting Ctrl+S, the restoring of the references packages starts.
Then we see the references added. For more information on the project.json file and its contents, please visit the below link:
Project.json
Integration to Cloud & optimized: This is another major boost feature added to MVC6 application. Now it comes integrated to the cloud with Microsoft Azure and also the optimizing and monitoring tool provided by Azure, i.e. Application Insights.
We will have a walk through of adding the cloud Web application and then a brief on Application insights as well.
Boosted Dependency Injection: Now MVC6 application has in built and integrated dependency injection facility. There is no more need for the packages like, Ninject, Unity, Structure Map3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. //Dependency Injection as well services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); }
The we normally inject the services into the constructor of the controllers. Is’nt that great!!
appsettings.json: As we know there is no Web.config file in our application, but we need to have a place where we have the settings required by the application at all stages. This is this place. In MVC6, they have had a upper hand over the JSON than the XML.
The connection strings, the other app settings file we used to add inside the Web.config will now be contained here, that to in Json format. An example like below:
"Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;Trusted_Connection=True;MultipleActiveResultSets=true" } }
global.json: This is a separate folder named Solution Items. here is the global.json file, which contains the solutions’s project references and their dependencies as well. Loos like below:
{ "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-rc1-update1" } }
The appsettings is initialized into the project in the Startup.cs file as below:
var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
The App_Start which had the RouteConfig.cs file also goes missing. In MVC is present inside the Startup.cs file as below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
Thus, lets have a look at the entry point of the application:
// Entry point for the application. public static void Main(string[] args) => WebApplication.Run(args);
Another nice feature is the segregation of the Models & View Models. The Model now only will deal with the Db Entities and the context, where as the ViewModel will deal with the model classes which are required in the View binding.
This was just a brief about MVC6, more information and application building will be shown in the upcoming articles on MVC6. Now lets jump start the deployment to azure.
Now lets discuss creating a new MVC6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explain you which will help understand better.
Thus, once the website is hosted on Azure, we can browse and run our application and share with anyone to navigate through our application. We came to know in this article how easy it is to deploy to cloud in the latest builds, making the lives of developers much easier. I will be sharing and covering the Application Insights in the next article which will follow this up. I hope this has helped in learning some facts about MVC6 and please post your feedback. Application Insights– upcoming.
JSON Java Script Object Notation , a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of a syntax for storing and passing data. Since it is Java script object notation, it uses the java script style of syntax, but actually is text only. It also is language independent. The format would look like below:
{"Books":[ {"name":"Asp.Net Mvc", "code":"111"}, {"name":"Angular Js", "code":"112"}, {"name":"Javascript", "code":"113"}, {"name":"CLR", "code":"114"} ]}
Now this, JSON object can be created and used to POST or GET in MVC application. Usually, when we do an ajax call, we get the HTML fragments and send them to the browser or append to any DOM elements. That is acceptable, but sending HTML elements with data is not advisable, so would not that be great to send data in a specific format and the browser assigns the data into the HTML. Here, JSON comes in handy. Lets see how. I will explain in simple terms and snippets for better understanding as this topic is not complex at all.
I will proceed with an anticipation that readers are aware of MVC (Model, View & Controller), as I will not be sharing the steps to create an MVC project. So, Lets start.
When we create a controller in an MVC project, we know the default type added is ActionResult, which is generic to other types of method types pre-defined like: ViewResult, JsonResult, etc.. Thus, for returning a JSON data, we can use either ActionResult or JsonResult,but preferably use JsonResult as we already know the type, the method will return. JsonResult, is actually a special ActionResult, which suggests the ViewEngine that an object of JSON type will be returned rather than normal HTML.
Lets see the snippet and then try and understand.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.MVC; using DemoJsonTest.Models; namespace DemoJsonTest.Controllers { public class EmployeeController : Controller { private Employee[] employeeData = { new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"}, new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"}, new Employee {Name:"Suraj Ray",EmpCode:"EMP041"} }; public ActionResult Index() { return View(); } public JsonResult GetEmployeeDataJson(string empCode) { var employee = employeeData.Where(emp => emp.EmpCode == empCode).SingleOrDefault(); return Json(employee, JsonRequestBehaviour.AllowGet); }
Thus,in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with few dummy data. Then the main part is the JsonReult method using which, we are filtering the data based on the parameter passed, here EmpCode and then returning the Json object. Mark here, we have used JsonRequestBehaviour.AllowGet. Now whats this. This has an interesting concept behind it. Usually, the browsers to avoid malicious sites trying to intercept JSON data returned, in response to a GET request, it does not respond to GET requests by default.
System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
The above is a part of the error thrown when we miss AllowGet. That is self explanatory actually.
We usually us ajax options, i.e. success method to process the JSON data received from the GET request and append or set to the HTML DOM elements.
<script type="text/javascript"> $.ajax({ url: "GET REQUEST URL", type:"GET", success: function(empData) { var trgt = $("#tblEmployee"); target.append("<tr><td>" + empData.Name + "</td><td>" + empData.EmpCode + "</td></tr>"); }, error: function() { //Do something.. } }); // ]]></script>
Thus, in the above snippet, we are fetching the data in JSON format from the GET response and binding to the table html dom.
A point to note here is that, when we assign/cast (actually) a model into JSON object and we explicitly specify few properties of the model and miss out on others, MVC framework is clever enough to first convert the model with each property into JSON and then assign default values to those properties which we have missed. Lets see an example of conversion:
{ "EmployeeId":0, "Name":"Suraj Sahoo", "EmpCode":"042", "IsActiveEmployee": false, "DepartmentId": null }
Mark here,that we have only specified the values of Name and the EmpCode, all other values assigned after JSON conversion by the MVC smart framework.
We saw and discussed a very simple and interesting topic regarding the JSON in MVC and how smartly MVC handles the conversion. This helps when we use API and then return JSON,XML to interchange and expose our data. JSON is actually an alternative to XML form of data exchange. For angular JS now a dayswhich is in demand,we use the API controller, return JSON data and take the advantage of Angular two-way binding.
I hope this helps the beginners out there learning MVC. This is a part of it. Enjoy coding. Open to suggestions. Don’t miss to add your feedback.
Hello folks!! Lets continue our journey of learning Angular JS. We have seen & discussed few topics already!
In this article we will discuss few concepts that are very essential to build an MVC project with Angular.
Lets see the topics we will be covering in thisΒ article:
This as the name suggests binds the values to the model associated to an element. This shows a two-way binding, i.e. when the value suppose in the textbox changes, the value for the model also binds and changes. The attribute used is ng-model, the code would be like:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div>Name : <input type="text" /> <h1>Welcome {{name}}</h1> </div>
This will update the value of text entered inside the text box and gets displayed in real time.
Interesting fact about the ng-model directive is that, the directive watches the model by reference not by value. It also provides validation to the particular field.
Angular scopes are the execution-context generated during the creation of a controller. We pass the scope object to the controller function. The scope is generally denoted as $scope. This is actually an object to which we add the properties to be accessed in the HTML page using the controller reference.
As the angular doc rightly says, it is actually the glue between the controller and the view. It comes with two referring API i.e. $watch (used to observe the model mutations) and $apply (used to propagate the changes done to the scope object property) Lets have a glance at the snippet:
angular.module('scopeTest', []).controller('TestController', function($scope) { $scope.username = Suraj; });
This is how the scope object is passed and initialized and assigned properties to be used inside the view.
Interesting Facts:
Controller function in Angular is a constructor function. Now what is a constructor function?
A constructor function in simple terms is when the new keyword is used before a function.
var constructorFunction = new Funciton(Parameters..);
Thus everytime a controller is instantiated it gets associated with a new Scope.
There are many in-built services provided by the Angular and also we can explicitly create our own services to have a loose coupling while using the Http Get Post services. These are actually singleton functions that are required to perform certain specified tasks. What singleton means is restricting the instantiation to a single object only.
As in MVC we follow Separation of concern, here also these services can be used to follow the loose coupling and binding.
As we can see here the reuse of the services can also be followed here. This is done using the injection of dependency into the controller function. We will look into the dependency in the next points.
Lets see how we declare a service in Angular.
var module = angular.module('TestApp', []); module.service('TestService', function(){ this.users = ['Suraj', 'CsharpCorner', 'Angular']; });
Here comes another concept known as Factory, which also behaves as a service function only.
var module = angular.module('TestApp', []); module.factory('TestFactory', function(){ var testFactory = {}; testFactory.users = ['Suraj', 'CsharpCorner', 'Angular']; return testFactory; });
The behavior is the same for both service and factory, but the difference is interesting. For the difference, take a closer look at the snippets mentioned above. In the first snippet where we have declared the service and we have added the ‘users’ to the reference of the service i.e. this keyword. Whereas, in the .factory declaration, we have used the testFactory object and assigned property users to it. While using the Services in the injection, we will have the object instance of the service becomes the reference to the methods and can be used in the injection for other controllers or services, while in case of factory, when that is injected, the value is directly provided which is returned by the function within.
The above discussed are explicit or user-defined services, now lets see the in-built services provided by the Angular. (Some of them)
var app = angular.module('TestApp', []); app.controller('TestCtrl', function($scope, $http) { $http.get("url").then(function (response) { $scope.testData= response.data; }); });
var app = angular.module('TestApp', []); app.controller('TestCtrl', function($scope, $interval) { $scope.theTime = new Date().toLocaleTimeString(); $interval(function () { $scope.theTime = new Date().toLocaleTimeString(); }, 1000); }); //reference for use from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_interval
This is an interesting and most debated topic and angular provides this out of the box concept.
Β Out of the box..
Dependency is required when we are looking for the loosely coupled codes, i.e. without directly exposing our services. The separation of concern is the major concern when DI comes into picture. Once our service is ready, we can inject to any other service or controller in Angular. The best example would be a Bakery shop.
Lets chalk out the plan with a simple snippet:
var app = angular.module('BakeryApp', []); app.service('BakeryService', function() { //Declare or pass the prices as arg this.Pizza = function(quantity) { return quantity * pizzaPrice }; this.Pastries =function(quantity) { return quantity * pastriesPrice }; this.Cakes= function(quantity) { return quantity * cakePrice}; }); //Injected Bakery Service to the 'BakeryCalculateService' app.service('BakeryCalculateService', function(BakeryService){ this.PizzaPrice = function(qty) { return BakeryService.Pizza(qty); }; this.CakePrice= function(qty) { return BakeryService.Cakes(qty); }; }); //Injected BakeryCalculateService. app.controller('BakeryPriceController', function($scope, BakeryCalculateService) { $scope.CalcPizzaRate= function() { $scope.PizzaRate = BakeryCalculateService.PizzaPrice ($scope.quantity); } $scope.CalcCakeRate= function() { $scope.answer = BakeryCalculateService.CakePrice($scope.quantity); } });
We can very well in the above example see the Dependency Injection and the separation of the main service, the layering that is set between the controller and the actual operations. This is very handy during maintenance as well. This is by law which every developer should abide by
Another interesting fact when we use the injection is the minification breakage. The angular code breaks when the injection is not done properly when the script files are usually bundled and minified.
The above Dependency Injection snippet we discussed, will break when the script is minified, bundled & deployed. The reason being, when minification takes place, it re-frames the variable names as ‘a’,’b’,’c’.., thus the parameters injected as $scope,$http will be now treated as a, b. Thus this will break as there is no meaning injecting a b, may it be a controller or a service.
To avoid that, we usually modify the snippet and use the Angular attribute $inject, wherever Dependency is injected.
var testController= function(myCtrlScope, $http) { //We included $scope and the $http service into our controller. } testController.$inject = ['$scope', '$http']
Since we are using $inject attribute on our controller,it would not be an issue using any name of the parameters to it.
Thus, we have discussed few interesting concepts this time and work around with live snippets. Still we have not discussed the integration of angular with an MVC app using API. We will discuss in the upcoming articles of the series, before that we will be clear on the basic stuffs that needs to be covered.
I hope this article helps. I am always open for corrections and suggestions.
Lets learn and share together.