Nuget Package Management

ASP.NET MVC – NuGet Package Management ”; Previous Next In this chapter, we will talk about NuGet which is a package manager for .NET and Visual Studio. NuGet can be used to find and install packages, that is, software pieces and assemblies and things that you want to use in your project. NuGet is not a tool that is specific to ASP.NET MVC projects. This is a tool that you can use inside of Visual Studio for console applications, WPF applications, Azure applications, any types of application. Package Management NuGet is a package manager, and is responsible for downloading, installing, updating, and configuring software in your system. From the term software we don’t mean end users software like Microsoft Word or Notepad 2, etc. but pieces of software, which you want to use in your project, assembly references. For example, assemblies you want to use might be mock, for mock object unit testing, or NHibernate for data access, and components you use when building your application. The above-mentioned components are open source software, but some NuGet packages you find are closed source software. Some of the packages you”ll find are even produced by Microsoft. The common theme along all the packages mentioned above, like mock and NHibernate, and Microsoft packages like a preview for the Entity Framework, is that they don”t come with Visual Studio by default. Without NuGet To install any of these components without NuGet, you will need the following steps. If you want to use one of those components, you need to find the home page for some particular project and look for a download link. Then once the project is downloaded, it”s typically in a ZIP format so you will need to extract it. If you didn”t download binaries, then you will first need to build the software and then reference it in your project. And many components at that point still require some configuration to get up and running. Using NuGet NuGet replaces all of the steps discussed earlier and you just need to say Add Package. NuGet knows where to download the latest version, it knows how to extract it, how to establish a reference to that component, and even configure it. This leaves you more time to just build the software. Let’s take a look at a simple example in which we will add support for Entity framework in our ASP.NET MVC project using NuGet. Step 1 − Install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution… It will open the NuGet Package Manager. Step 2 − Search for Entity framework in the search box. Step 3 − Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog. Step 4 − Click Ok to continue. Step 5 − Click the ‘I Accept’ button to start the installation. Once the Entity Framework is installed you will see the message in out window as shown above. When you install a package with NuGet, you will see a new packages directory in the same folder as the solution file hosting your project. This package directory contains all the packages that you have installed for any of the projects in that solution. In other words, NuGet is not downloading packages into a central location, it”s storing them on a per solution basis. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Deployment

ASP.NET MVC – Deployment ”; Previous Next In this chapter, we will be covering how to deploy ASP.NET MVC application. After understating different concepts in ASP.NET MVC applications, now it’s time to understand the deployment process. So, whenever we are building any MVC application we are basically producing a dll file associated for the same with all the application settings and logic inside and these dlls are in the bin directory of the project as shown in the following screenshot. Publishing to Microsoft Azure Let’s take a look at a simple example in which we will deploy our example to Microsoft Azure. Step 1 − Right-click on the project in the Solution Explorer and select Publish as shown in the following screenshot. Step 2 − You will see the Publish Web dialog. Click on the Microsoft Azure Web Apps. It will display the ‘Sign in’ page. Step 3 − Enter credentials for the Microsoft Azure Subscription. Once you’re successfully connected to your Azure account, you will see the following dialog. Step 4 − Click ‘New’ button. Step 5 − Enter the desired information on the above dialog such as Web App name, which must be a unique name. You will also need to enter App service plan, resource group, and then select your region. Step 6 − Click ‘Next’ button to continue. Step 7 − Click the ellipsis mark ‘…’ to select the connection string. Step 8 − Select the server name and then choose the Windows Authentication option. Select the database name as well. Now you will see that the connection string is generated for you. Step 9 − Click ‘Next’ to continue. Step 10 − To check all the files and dlls which we will be publishing to Azure, click the Start Preview. Click ‘Publish’ button to publish your application. Once the application is successfully published to Azure, you will see the message in the output window. Step 11 − Now open your browser and enter the following URL ‘http://mymvcdemoapp.azurewebsites.net/employees’ and you will see the list of employees. Step 12 − Now if you go to your Azure portal and click ‘App Services’, then you see that your application is deployed to Azure. Step 13 − Click the name of your app and you will see the information related to that application such as URL, Status, Location, etc. We have seen so far how to publish a web application to Azure app, after the application is created. You can also create an application, which will be deployed to Azure. Let’s create a new ASP.NET MVC application. Step 1 − Click Ok and you will see the following dialog. Step 2 − Select MVC template and also check Host in the Cloud checkbox. Click Ok. When the Configure Microsoft Azure Web App Settings dialog appears, make sure that you are signed in to Azure. You can see the default name, but you can also change the Web App name. Step 3 − Enter the desired information as shown in the following screenshot. Step 4 − Select the ‘Create new server’ from the Database server dropdown and you will see the additional field. Step 5 − Enter the Database server, username, and password. Click Ok. Step 6 − Once the project is created, run the application and you will see that it is running on the localhost. Step 7 − To deploy these applications to Azure, right-click on the project in the solution explorer and select ‘Publish’. You will see the following dialog. Step 8 − Click the ‘Microsoft Azure Web Apps’. Step 9 − Select your application name from the Existing Web Apps and click Ok. Step 10 − Click the ‘Validate Connection’ button to check for the connection on Azure. Step 11 − Click ‘Next’ to continue. Now you will see that the connection string is already generated by default. Step 12 − Click ‘Next’ to continue. Step 13 − To check all the files and dlls which will be published to Azure, click the ‘Start Preview’. Step 14 − Click ‘Publish’ button to publish your application. Once the application is successfully published to Azure, you will see the message in the output window. You will also see that the application is now running from the cloud. Let’s go to Azure portal again. You will see the app here as well. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Useful Resources

ASP.NET MVC – Useful Resources ”; Previous Next The following resources contain additional information on ASP.NET MVC. Please use them to get more in-depth knowledge on this topic. Useful Video Courses ASP.NET Core 3 MVC Application with MongoDB Most Popular 45 Lectures 4.5 hours Kaushik Roy Chowdhury More Detail Learn ASP.Net MVC and Entity Framework (Database First) Most Popular 20 Lectures 5 hours Trevoir Williams More Detail ASP.Net Core MVC Training Course 53 Lectures 3 hours Skillbakery More Detail Spring MVC Essentials: A Primary Course for Java Spring MVC 25 Lectures 3.5 hours TELCOMA Global More Detail ASP.NET Core MVC – A Step by Step Course 37 Lectures 7 hours TELCOMA Global More Detail .Net Developer Course Using ASP.NET MVC Core, C#, OOP, SQL Entity Framework Best Seller 89 Lectures 7.5 hours Mustafa Radaideh More Detail Print Page Previous Next Advertisements ”;

ASP.NET MVC – Selectors

ASP.NET MVC – Selectors ”; Previous Next Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request. It plays a very crucial role when you are writing your action methods. These selectors will decide the behavior of the method invocation based on the modified name given in front of the action method. It is usually used to alias the name of the action method. There are three types of action selector attributes − ActionName NonAction ActionVerbs ActionName This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name. Let’s take a look at a simple example from the last chapter in which we have HomeController containing two action methods. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return “This is ASP.Net MVC Filters Tutorial”; } public string GetCurrentTime(){ return DateTime.Now.ToString(“T”); } } } Let’s apply the the ActionName selector for GetCurrentTime by writing [ActionName(“CurrentTime”)] above the GetCurrentTime() as shown in the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return “This is ASP.Net MVC Filters Tutorial”; } [ActionName(“CurrentTime”)] public string GetCurrentTime(){ return DateTime.Now.ToString(“T”); } } } Now run this application and enter the following URL in the browser http://localhost:62833/Home/CurrentTime, you will receive the following output. You can see that we have used the CurrentTime instead of the original action name, which is GetCurrentTime in the above URL. NonAction NonAction is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when you want that a method shouldn’t be treated as an action method. Let’s take a look at a simple example by adding another method in HomeController and also apply the NonAction attribute using the following code. using MVCFiltersDemo.ActionFilters; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return “This is ASP.Net MVC Filters Tutorial”; } [ActionName(“CurrentTime”)] public string GetCurrentTime(){ return TimeString(); } [NonAction] public string TimeString(){ return “Time is ” + DateTime.Now.ToString(“T”); } } } The new method TimeString is called from the GetCurrentTime() but you can’t use it as action in URL. Let’s run this application and specify the following URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the following output. Let us now check the /TimeString as action in the URL and see what happens. You can see that it gives ‘404—Not Found’ error. ActionVerbs Another selector filter that you can apply is the ActionVerbs attributes. So this restricts the indication of a specific action to specific HttpVerbs. You can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request. MVC framework supports the following ActionVerbs. HttpGet HttpPost HttpPut HttpDelete HttpOptions HttpPatch Let’s take a look at a simple example in which we will create EmployeeController. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee public ActionResult Search(string name = “No name Entered”){ var input = Server.HtmlEncode(name); return Content(input); } } } Now let’s add another action method with the same name using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee //public ActionResult Index() //{ // return View(); //} public ActionResult Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } public ActionResult Search(){ var input = “Another Search action”; return Content(input); } } } When you run this application, it will give an error because the MVC framework is unable to figure out which action method should be picked up for the request. Let us specify the HttpGet ActionVerb with the action you want as response using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee //public ActionResult Index() //{ // return View(); //} public ActionResult Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } [HttpGet] public ActionResult Search(){ var input = “Another Search action”; return Content(input); } } } When you run this application, you will receive the following output. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Self-hosting

ASP.NET MVC – Self-hosting ”; Previous Next In this chapter, we will cover Self-Hosting. Self-Hosting creates a runtime environment for the application to run in any environment say MAC, or in Linux box, etc. Self-Hosting also means it will have a mini CLR version. Deploy using File System Let’s take a look at a simple example of self-hosting. Step 1 − Once your ASP.NET MVC application is completed and you want to use selfhosting, right-click on the Project in the solution explorer. You will see the following dialog. Step 2 − Click the ‘Custom’ option, which will display the New Custom Profile dialog. Step 3 − Enter the profile name and click Ok. Step 4 − Select the File System from the Publish method dropdown list and also specify the target location. Click ‘Next’ button. Step 5 − Expand the File Publish Options. Step 6 − Check the ‘Delete all existing files prior to publish’ and ‘Precompile during publishing’ checkboxes and click ‘Next’ to continue. Step 7 − Click ‘Publish’ button, it will publish the files at the desired location. You will see all the files and folders in the target location on your system. It will have all the files required to get deployed on the localhost. Step 8 − Now open the Turn Windows Feature on or off and Expand Internet Information Services → World Wide Web Services → Application Development Features. Step 9 − Check the checkboxes as shown in the above screenshot and click Ok. Step 10 − Let’s open the IIS Manager as shown in the following screenshot. Step 11 − You will see different connections on the left side of the screen, right-click on MyWebSite. Step 12 − Select the ‘Convert to Application’ option. As you can see, its physical path is the same as we have mentioned above while publishing, using the File system. Step 13 − Click Ok to continue. Now you can see that its icon has changed. Step 14 − Open your browser and specify the following URL http://localhost/MyWebSite You can see that it is running from the folder which we have specified during deployment. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Bootstrap

ASP.NET MVC – Bootstrap ”; Previous Next In this chapter, we will look at Bootstrap which is a front-end framework now included with ASP.NET and MVC. It is a popular front-end tool kit for web applications, and will help you build a user interface with HTML, CSS, and JavaScript. It was originally created by web developers at Twitter for personal use, however, it is now an open source and has become popular with designers and developers because of its flexiblility and ease of use. You can use Bootstrap to create an interface that looks good on everything from large desktop displays to small mobile screens. In this chapter, we will also look at how Bootstrap can work with your layout views to structure the look of an application. Bootstrap provides all the pieces you need for layout, buttons, forms, menus, widgets, picture carousels, labels, badges, typography, and all sorts of features. Since Bootstrap is all HTML, CSS and JavaScript, all open standards, you can use it with any framework including ASP.NET MVC. When you start a new MVC project, Bootstrap will be present, meaning you”ll find Bootstrap.css and Bootstrap.js in your project. Let’s create a new ASP.NET Web Application. Enter the name of the project, let’s say ‘MVCBootstrap’ and click Ok. You will see the following dialog. In this dialog, if you select the empty template, you will get an empty web application and there will be no Bootstrap present. There won”t be any controllers or any other script files either. Now select the MVC template and click Ok. When Visual Studio creates this solution, one of the packages that it will download and install into the project will be the Bootstrap NuGet package. You can verify by going to packages.config and you can see the Bootstrap version 3 package. You can also see the Content folder which contains different css files. Run this application and you will see the following page. When this page appears, most of the layout and styling that you see is layout and styling that has been applied by Bootstrap. It includes the navigation bar at the top with the links as well as the display that is advertising ASP.NET. It also includes all of these pieces down about getting started and getting more libraries and web hosting. If you expand the browser just a little bit more, those will actually lay out side by side and that”s part of Bootstrap”s responsive design features. If you look under the content folder, you will find the Bootstrap.css file. The NuGet package also gives a minified version of that file that”s a little bit smaller. Under scripts, you will find Bootstrap.js, that”s required for some of the components of Bootstrap. It does have a dependency on jQuery and fortunately jQuery is also installed in this project and there”s a minified version of the Bootstrap JavaScript file. Now the question is, where are all these added in the application? You might expect, that it would be in the layout template, the layout view for this project which is under View/Shared/_layout.cshtml. The layout view controls the structure of the UI. Following is the complete code in _layout.cshtml file. <!DOCTYPE html> <html> <head> <meta charset = “utf-8” /> <meta name = “viewport” content = “width = device-width, initial-scale = 1.0”> <title>@ViewBag.Title – My ASP.NET Application</title> @Styles.Render(“~/Content/css”) @Scripts.Render(“~/bundles/modernizr”) </head> <body> <div class = “navbar navbar-inverse navbar-fixed-top”> <div class = “container”> <div class = “navbar-header”> <button type = “button” class = “navbar-toggle” datatoggle = “collapse” data-target = “.navbar-collapse”> <span class = “icon-bar”></span> <span class = “icon-bar”></span> <span class = “icon-bar”></span> </button> @Html.ActionLink(“Application name”, “Index”, “Home”, new { area = “” }, new { @class = “navbar-brand” }) </div> <div class = “navbar-collapse collapse”> <ul class = “nav navbar-nav”> <li>@Html.ActionLink(“Home”, “Index”, “Home”)</li> <li>@Html.ActionLink(“About”, “About”, “Home”)</li> <li>@Html.ActionLink(“Contact”, “Contact”, “Home”)</li> </ul> @Html.Partial(“_LoginPartial”) </div> </div> </div> <div class = “container body-content”> @RenderBody() <hr /> <footer> <p>© @DateTime.Now.Year – My ASP.NET Application</p> </footer> </div> @Scripts.Render(“~/bundles/jquery”) @Scripts.Render(“~/bundles/bootstrap”) @RenderSection(“scripts”, required: false) </body> </html> In the above code there are two things to note. First at the top, after <title> you will see the following line of code. @Styles.Render(“~/Content/css”) The Styles.Render for Content/css is actually where the Bootstrap.css file is going to be included, and at the bottom, you will see the following line of code. @Scripts.Render(“~/bundles/bootstrap”) It is rendering the Bootstrap script. So in order to find out what exactly is inside of these bundles, we”ll have to go into the BundleConfig file, which is in App_Start folder. In BundleConfig, you can see at the bottom that the CSS bundle includes both Bootstrap.css and our custom site.css. bundles.Add(new StyleBundle(“~/Content/css”).Include( “~/Content/bootstrap.css”, “~/Content/site.css”)); It is a place where we can add our own style sheets to customize the look of the application. You can also see the Bootstrap bundle that appears before the CSS bundle that includes Bootstrap.js, and another JavaScript file, respond.js. bundles.Add(new ScriptBundle(“~/bundles/bootstrap”).Include( “~/Scripts/bootstrap.js”, “~/Scripts/respond.js”)); Let’s comment Bootstrap.css as shown in the following code. bundles.Add(new StyleBundle(“~/Content/css”).Include( //”~/Content/bootstrap.css”, “~/Content/site.css”)); Run this application again, just to give you an idea of what Bootstrap is doing, because now the only styles that are available are the styles that are in site.css. As you can see we lost the layout, the navigation bar at the top of the page. Now everything looks ordinary and boring. Let us now see what Bootstrap is all about. There”s a couple of things that Bootstrap just does automatically and there”s a couple of things that Bootstrap can do for you when you add classes and have the right HTML structure. If you look at the _layout.cshtml file, you will see the navbar class as shown in the following code. <div class = “navbar navbar-inverse navbar-fixed-top”> <div class = “container”> <div class = “navbar-header”> <button type = “button” class = “navbar-toggle” datatoggle = “collapse” data-target = “.navbar-collapse”> <span class = “icon-bar”></span> <span class = “icon-bar”></span> <span class = “icon-bar”></span> </button> <a class = “navbar-brand” href = “/”>Application name</a> </div> <div class = “navbar-collapse collapse”>

ASP.NET MVC – Web API

ASP.NET MVC – Web API ”; Previous Next 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. When you”re building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web. The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints end up being a separate URI. Let’s take a look at a simple example of Web API by creating a new ASP.NET Web Application. Step 1 − Open the Visual Studio and click File → New → Project menu option. A new Project dialog opens. Step 2 − From the left pane, select Templates → Visual C# → Web. Step 3 − In the middle pane, select ASP.NET Web Application Enter project name WebAPIDemo in the Name field and click Ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project. Step 4 − To keep things simple, select the Empty option and check the Web API checkbox in the ‘Add folders and core references for’ section and click Ok. Step 5 − It will create a basic MVC project with minimal predefined content. Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window. Step 6 − Now we need to add a model. Right-click on the Models folder in the solution explorer and select Add → Class. You will now see the Add New Item dialog. Step 7 − Select Class in the middle pan and enter Employee.cs in the name field. Step 8 − Add some properties to Employee class using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPIDemo.Models { public class Employee{ public int ID { get; set; } public string Name { get; set; } public DateTime JoiningDate { get; set; } public int Age { get; set; } } } Step 9 − Let’s add the controller. Right-click on the controller folder in the solution explorer and select Add → Controller. It will display the Add Scaffold dialog. Step 10 − Select the Web API 2 Controller – Empty option. This template will create an Index method with default action for controller. Step 11 − Click ‘Add’ button and the Add Controller dialog will appear. Step 12 − Set the name to EmployeesController and click ‘Add’ button. You will see a new C# file ‘EmployeeController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions. using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using WebAPIDemo.Models; namespace WebAPIDemo.Controllers{ public class EmployeesController : ApiController{ Employee[] employees = new Employee[]{ new Employee { ID = 1, Name = “Mark”, JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 30 }, new Employee { ID = 2, Name = “Allan”, JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 35 }, new Employee { ID = 3, Name = “Johny”, JoiningDate = DateTime.Parse(DateTime.Today.ToString()), Age = 21 } }; public IEnumerable<Employee> GetAllEmployees(){ return employees; } public IHttpActionResult GetEmployee(int id){ var employee = employees.FirstOrDefault((p) => p.ID == id); if (employee == null){ return NotFound(); } return Ok(employee); } } } Step 13 − Run this application and specify /api/employees/ at the end of the URL and press ‘Enter’. You will see the following output. Step 14 − Let us specify the following URL http://localhost:63457/api/employees/1 and you will see the following output. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Scaffolding

ASP.NET MVC – Scaffolding ”; Previous Next ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project. As you have seen that we have created the views for Index, Create, Edit actions and also need to update the actions methods as well. But ASP.Net MVC provides an easier way to create all these Views and action methods using scaffolding. Let’s take a look at a simple example. We will create the same example which contains a model class Employee, but this time we will use scaffolding. Step 1 − Open the Visual Studio and click on File → New → Project menu option. A new Project dialog opens. Step 2 − From the left pane, select Templates → Visual C# → Web. Step 3 − In the middle pane, select ASP.NET Web Application. Step 4 − Enter the project name ‘MVCScaffoldingDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project. Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’section and click Ok. It will create a basic MVC project with minimal predefined content. Once the project is created by Visual Studio, you will see a number of files and folders displayed in the Solution Explorer window. Add Entity Framework Support First step is to install the Entity Framework. Right-click on the project and select NuGet Package Manager → Manage NuGet Packages for Solution… It will open the ‘NuGet Package Manager’. Search for Entity framework in the search box. Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog. Click Ok to continue. Click ‘I Accept’ button to start installation. Once the Entity Framework is installed you will see the message in the out window as shown in the above screenshot. Add Model To add a model, right-click on the Models folder in the solution explorer and select Add → Class. You will see the ‘Add New Item’ dialog. Select Class in the middle pan and enter Employee.cs in the name field. Add some properties to Employee class using the following code. using System; namespace MVCScaffoldingDemo.Models { public class Employee{ public int ID { get; set; } public string Name { get; set; } public DateTime JoiningDate { get; set; } public int Age { get; set; } } } Add DBContext We have an Employee Model, now we need to add another class, which will communicate with Entity Framework to retrieve and save the data. Following is the complete code in Employee.cs file. using System; using System.Data.Entity; namespace MVCScaffoldingDemo.Models{ public class Employee{ public int ID { get; set; } public string Name { get; set; } public DateTime JoiningDate { get; set; } public int Age { get; set; } } public class EmpDBContext : DbContext{ public DbSet<Employee> Employees { get; set; } } } As you can see ‘EmpDBContext’ is derived from an EF class known as ‘DbContext’. In this class, we have one property with the name DbSet, which basically represents the entity which you want to query and save. Now let’s build a solution and you will see the message when the project is successfully build. Add a Scaffolded Item To add a scaffold, right-click on Controllers folder in the Solution Explorer and select Add → New Scaffolded Item. It will display the Add Scaffold dialog. Select MVC 5 Controller with views, using Entity Framework in the middle pane and click ‘Add’ button, which will display the Add Controller dialog. Select Employee from the Model class dropdown and EmpDBContext from the Data context class dropdown. You will also see that the controller name is selected by default. Click ‘Add’ button to continue and you will see the following code in the EmployeesController, which is created by Visual Studio using Scaffolding. using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Mvc; using MVCScaffoldingDemo.Models; namespace MVCScaffoldingDemo.Controllers { public class EmployeesController : Controller{ private EmpDBContext db = new EmpDBContext(); // GET: Employees public ActionResult Index(){ return View(db.Employees.ToList()); } // GET: Employees/Details/5 public ActionResult Details(int? id){ if (id == null){ return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null){ return HttpNotFound(); } return View(employee); } // GET: Employees/Create public ActionResult Create(){ return View(); } // POST: Employees/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = “ID,Name,JoiningDate,Age”)] Employee employee){ if (ModelState.IsValid){ db.Employees.Add(employee); db.SaveChanges(); return RedirectToAction(“Index”); } return View(employee); } // GET: Employees/Edit/5 public ActionResult Edit(int? id){ if (id == null){ return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null){ return HttpNotFound(); } return View(employee); } // POST: Employees/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = “ID,Name,JoiningDate,Age”)]Employee employee){ if (ModelState.IsValid){ db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction(“Index”); } return View(employee); } // GET: Employees/Delete/5 public ActionResult Delete(int? id){ if (id == null){ return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null){ return HttpNotFound(); } return View(employee); } // POST: Employees/Delete/5 [HttpPost, ActionName(“Delete”)] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id){ Employee employee = db.Employees.Find(id); db.Employees.Remove(employee); db.SaveChanges(); return RedirectToAction(“Index”); } protected override void Dispose(bool disposing){ if (disposing){ db.Dispose(); } base.Dispose(disposing); } } } Run your application and specify the following URL http://localhost:59359/employees. You will see the following output. You can see there is no data in the View, because we have not added any records to the database, which is created by Visual Studio. Let’s add one record from the browser

ASP.NET MVC – Caching

ASP.NET MVC – Caching ”; Previous Next In this chapter, we will be focusing on one of the most common ASP.NET techniques like Caching to improve the performance of the application. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache. In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory. Hence, any future request coming for the same action in that controller will be returned from the cached result. That way, the same content does not need to be generated each and every time the same controller action is invoked. Why Caching? We need caching in many different scenarios to improve the performance of an application. For example, you have an ASP.NET MVC application, which displays a list employees. Now when these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view. Hence you can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action. Caching enables you to avoid performing redundant work on the server. Let’s take a look at a simple example of caching in our project. [OutputCache(Duration = 60)] public ActionResult Index(){ var employees = from e in db.Employees orderby e.ID select e; return View(employees); } As you can see, we have added “OutputCache” attribute on the index action of the EmployeeController. Now to understand this concept, let us run this application in debugger mode and also insert a breakpoint in the Index action method. Specify the following URL http://localhost:63004/employee, and press ‘Enter’. You will see that the breakpoint is hit in the Index action method. Press ‘F5’ button to continue and you will see the list of employees on your view, which are retrieved from the database. Refresh the browser again within 60 seconds and you will see that the breakpoint is not hit this time. This is because we have used output cache with duration of seconds. So it will cache this result for 60 seconds and when you refresh the browser, it will get the result from the cache, and it won’t load the content from the database server. In addition to duration parameter, there are other settings options as well which you can use with output cache. These settings are not only for MVC framework but it is inherited from ASP.Net Caching. Varying the Output Cache In some cases, you might want different cached versions, such as, when you create a detail page, then when you click on the detailed link you will get details for the selected employee. But first we need to create the detail view. For this, right-click on the Details action method from the EmployeeController and select Add View… You will see the Details name is selected by default. Now select Details from the Template dropdown and Employee from the Model class dropdown. Click ‘Add’ to continue and you will see the Details.cshtml. @model MVCSimpleApp.Models.Employee @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name = “viewport” content = “width = device-width” /> <title>Details</title> </head> <body> <div> <h4>Employee</h4> <hr /> <dl class = “dl-horizontal”> <dt> @Html.DisplayNameFor(model => model.Name) </dt> <dd> @Html.DisplayFor(model => model.Name) </dd> <dt> @Html.DisplayNameFor(model => model.JoiningDate) </dt> <dd> @Html.DisplayFor(model => model.JoiningDate) </dd> <dt> @Html.DisplayNameFor(model => model.Age) </dt> <dd> @Html.DisplayFor(model => model.Age) </dd> </dl> </div> <p> @Html.ActionLink(“Edit”, “Edit”, new { id = Model.ID }) | @Html.ActionLink(“Back to List”, “Index”) </p> </body> </html> You can take advantage of the VaryByParam property of the [OutputCache] attribute. This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies. Following is the implementation of Details action. // GET: Employee/Details/5 [OutputCache(Duration = int.MaxValue, VaryByParam = “id”)] public ActionResult Details(int id){ var employee = db.Employees.SingleOrDefault(e => e.ID == id); return View(employee); } When the above code is compiled and executed, you will receive the following output by specifying the URL http://localhost:63004/employee. Click on the Details link of any link and you will see the details view of that particular employee. The Details() action includes a VaryByParam property with the value “Id”. When different values of the Id parameter are passed to the controller action, different cached versions of the Details view are generated. It is important to understand that using the VaryByParam property results in more caching. A different cached version of the Details view is created for each different version of the Id parameter. Cache Profile You can create a cache profile in the web.config file. It is an alternative to configuring output cache properties by modifying properties of the [OutputCache] attribute. It offers a couple of important advantages which are as follows. Controls how controller actions cache content in one central location. Creates one cache profile and apply the profile to several controllers or controller actions. Modifies the web configuration file without recompiling your application. Disables caching for an application that has already been deployed to production. Let’s take a look at a simple example of cache profile by creating the cache profile in web.config file. The <caching> section must appear within the <system.web> section. <caching> <outputCacheSettings> <outputCacheProfiles> <add name = “Cache10Min” duration = “600” varyByParam = “none”/> </outputCacheProfiles> </outputCacheSettings> </caching> You can apply the Cache10Min profile to a controller action with the [OutputCache] attribute which is as follows. [OutputCache(CacheProfile = “Cache10Min”)] public ActionResult Index(){ var employees = from e in db.Employees orderby e.ID select

ASP.NET MVC – Actions

ASP.NET MVC – Actions ”; Previous Next ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions. For example, enter a URL into the browser, click on any particular link, and submit a form, etc. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method. The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc. Request Processing Actions are the ultimate request destination in an MVC application and it uses the controller base class. Let”s take a look at the request processing. When a URL arrives, like /Home/index, it is the UrlRoutingModule that inspects and understands that something configured within the routing table knows how to handle that URL. The UrlRoutingModule puts together the information we”ve configured in the routing table and hands over control to the MVC route handler. The MVC route handler passes the controller over to the MvcHandler which is an HTTP handler. MvcHandler uses a controller factory to instantiate the controller and it knows what controller to instantiate because it looks in the RouteData for that controller value. Once the MvcHandler has a controller, the only thing that MvcHandler knows about is IController Interface, so it simply tells the controller to execute. When it tells the controller to execute, that”s been derived from the MVC”s controller base class. The Execute method creates an action invoker and tells that action invoker to go and find a method to invoke, find an action to invoke. The action invoker, again, looks in the RouteData and finds that action parameter that”s been passed along from the routing engine. Types of Action Actions basically return different types of action results. The ActionResult class is the base for all action results. Following is the list of different kind of action results and its behavior. Sr.No. Name and Behavior 1 ContentResult Returns a string 2 FileContentResult Returns file content 3 FilePathResult Returns file content 4 FileStreamResult Returns file content 5 EmptyResult Returns nothing 6 JavaScriptResult Returns script for execution 7 JsonResult Returns JSON formatted data 8 RedirectToResult Redirects to the specified URL 9 HttpUnauthorizedResult Returns 403 HTTP Status code 10 RedirectToRouteResult Redirects to different action/different controller action 11 ViewResult Received as a response for view engine 12 PartialViewResult Received as a response for view engine Let’s have a look at a simple example from the previous chapter in which we have created an EmployeeController. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee public ActionResult Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } } } When you request the following URL http://localhost:61465/Employee/Mark, then you will receive the following output as an action. Add Controller Let us add one another controller. Step 1 − Right-click on Controllers folder and select Add → Controller. It will display the Add Scaffold dialog. Step 2 − Select the MVC 5 Controller – Empty option and click ‘Add’ button. The Add Controller dialog will appear. Step 3 − Set the name to CustomerController and click ‘Add’ button. Now you will see a new C# file ‘CustomerController.cs’ in the Controllers folder, which is open for editing in Visual Studio as well. Similarly, add one more controller with name HomeController. Following is the HomeController.cs class implementation. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return “This is Home Controller”; } } } Step 4 − Run this application and you will receive the following output. Step 5 − Add the following code in Customer controller, which we have created above. public string GetAllCustomers(){ return @”<ul> <li>Ali Raza</li> <li>Mark Upston</li> <li>Allan Bommer</li> <li>Greg Jerry</li> </ul>”; } Step 6 − Run this application and request for http://localhost:61465/Customer/GetAllCustomers. You will see the following output. You can also redirect to actions for the same controller or even for a different controller. Following is a simple example in which we will redirect from HomeController to Customer Controller by changing the code in HomeController using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers{ public class HomeController : Controller{ // GET: Home public ActionResult Index(){ return RedirectToAction(“GetAllCustomers”,”Customer”); } } } As you can see, we have used the RedirectToAction() method ActionResult, which takes two parameters, action name and controller name. When you run this application, you will see the default route will redirect it to /Customer/GetAllCustomers Print Page Previous Next Advertisements ”;