MVC Framework – Ajax Support ”; Previous Next As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your application, you can ignore this step. <add key = “UnobtrusiveJavaScriptEnabled” value = “true” /> After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery libraries here using the following code − <script src = “~/Scripts/jquery-ui-1.8.24.min.js” type = “text/javascript”> </script> <script src = “~/Scripts/jquery.unobtrusive-ajax.min.js” type = “text/javascript”> </script> Create an Unobtrusive Ajax Application In the example that follows, we will create a form which will display the list of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the list of users belonging to this category using unobtrusive AJAX setup. Step 1 − Create a Model file Model.cs and copy the following code. using System; namespace MVCAjaxSupportExample.Models { public class User { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Role Role { get; set; } } public enum Role { Admin, Normal, Guest } } Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MVCAjaxSupportExample.Models; namespace MVCAjaxSupportExample.Controllers { public class UserController : Controller { private readonly User[] userData = { new User {FirstName = “Edy”, LastName = “Clooney”, Role = Role.Admin}, new User {FirstName = “David”, LastName = “Sanderson”, Role = Role.Admin}, new User {FirstName = “Pandy”, LastName = “Griffyth”, Role = Role.Normal}, new User {FirstName = “Joe”, LastName = “Gubbins”, Role = Role.Normal}, new User {FirstName = “Mike”, LastName = “Smith”, Role = Role.Guest} }; public ActionResult Index() { return View(userData); } public PartialViewResult GetUserData(string selectedRole = “All”) { IEnumerable data = userData; if (selectedRole != “All”) { var selected = (Role) Enum.Parse(typeof (Role), selectedRole); data = userData.Where(p => p.Role == selected); } return PartialView(data); } public ActionResult GetUser(string selectedRole = “All”) { return View((object) selectedRole); } } } Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render list of users based on the selected role from the dropdown. @model IEnumerable<MVCAjaxSupportExample.Models.User> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.BirthDate) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.BirthDate) </td> <td> </td> </tr> } </table> Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller”s GetUserData Action. @using MVCAjaxSupportExample.Models @model string @{ ViewBag.Title = “GetUser”; AjaxOptions ajaxOpts = new AjaxOptions { UpdateTargetId = “tableBody” }; } <h2>Get User</h2> <table> <thead> <tr> <th>First</th> <th>Last</th> <th>Role</th> </tr> </thead> <tbody id=”tableBody”> @Html.Action(“GetUserData”, new {selectedRole = Model }) </tbody> </table> @using (Ajax.BeginForm(“GetUser”, ajaxOpts)) { <div> @Html.DropDownList(“selectedRole”, new SelectList( new [] {“All”}.Concat(Enum.GetNames(typeof(Role))))) <button type=”submit”>Submit</button> </div> } Step 5 − Finally, change the Route.config entries to launch the User Controller. defaults: new { controller = “User”, action = “GetUser”, id = UrlParameter.Optional } Step 6 − Run the application which will look like the following screenshot. If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page. Print Page Previous Next Advertisements ”;
Category: mvc Framework
MVC Framework – Controllers
MVC Framework – Controllers ”; Previous Next Asp.net MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC application, a controller is responsible for returning the response to that request. The controller can perform one or more actions. The controller action can return different types of action results to a particular request. The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receives an input from the users via the View, then processes the user”s data with the help of Model and passes the results back to the View. Create a Controller To create a Controller − Step 1 − Create an MVC Empty Application and then right-click on the Controller folder in your MVC application. Step 2 − Select the menu option Add → Controller. After selection, the Add Controller dialog is displayed. Name the Controller as DemoController. A Controller class file will be created as shown in the following screenshot. Create a Controller with IController In the MVC Framework, controller classes must implement the IController interface from the System.Web.Mvc namespace. public interface IController { void Execute(RequestContext requestContext); } This is a very simple interface. The sole method, Execute, is invoked when a request is targeted at the controller class. The MVC Framework knows which controller class has been targeted in a request by reading the value of the controller property generated by the routing data. Step 1 − Add a new class file and name it as DemoCustomController. Now modify this class to inherit IController interface. Step 2 − Copy the following code inside this class. public class DemoCustomController:IController { public void Execute(System.Web.Routing.RequestContext requestContext) { var controller = (string)requestContext.RouteData.Values[“controller”]; var action = (string)requestContext.RouteData.Values[“action”]; requestContext.HttpContext.Response.Write( string.Format(“Controller: {0}, Action: {1}”, controller, action)); } } Step 3 − Run the application and you will receive the following output. Print Page Previous Next Advertisements ”;
MVC Framework – Discussion
Discuss MVC Framework ”; Previous Next As per the official definition, Model-View-Controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. Print Page Previous Next Advertisements ”;
Exception Handling
MVC Framework – Exception Handling ”; Previous Next In ASP.NET, error handling is done using the standard try catch approach or using application events. ASP.NET MVC comes with built-in support for exception handling using a feature known as exception filters. We are going to learn two approaches here: one with overriding the onException method and another by defining the HandleError filters. Override OnException Method This approach is used when we want to handle all the exceptions across the Action methods at the controller level. To understand this approach, create an MVC application (follow the steps covered in previous chapters). Now add a new Controller class and add the following code which overrides the onException method and explicitly throws an error in our Action method − Now let us create a common View named Error which will be shown to the user when any exception happens in the application. Inside the Views folder, create a new folder called Shared and add a new View named Error. Copy the following code inside the newly created Error.cshtml − If you try to run the application now, it will give the following result. The above code renders the Error View when any exception occurs in any of the action methods within this controller. The advantage of this approach is that multiple actions within the same controller can share this error handling logic. However, the disadvantage is that we cannot use the same error handling logic across multiple controllers. HandleError Attribute The HandleError Attribute is one of the action filters that we studied in Filters and Action Filters chapter. The HandleErrorAttribute is the default implementation of IExceptionFilter. This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web.config. Open the web.config and place the following code inside system.web and set its value as On. <customErrors mode = “On”/> We already have the Error View created inside the Shared folder under Views. This time change the code of this View file to the following, to strongly-type it with the HandleErrorInfo model (which is present under System.Web.MVC). @model System.Web.Mvc.HandleErrorInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name = “viewport” content = “width = device-width” /> <title>Error</title> </head> <body> <h2> Sorry, an error occurred while processing your request. </h2> <h2>Exception details</h2> <p> Controller: @Model.ControllerName <br> Action: @Model.ActionName Exception: @Model.Exception </p> </body> </html> Now place the following code in your controller file which specifies [HandleError] attribute at the Controller file. using System; using System.Data.Common; using System.Web.Mvc; namespace ExceptionHandlingMVC.Controllers { [HandleError] public class ExceptionHandlingController : Controller { public ActionResult TestMethod() { throw new Exception(“Test Exception”); return View(); } } } If you try to run the application now, you will get an error similar to shown in the following screenshot. As you can see, this time the error contains more information about the Controller and Action related details. In this manner, the HandleError can be used at any level and across controllers to handle such errors. Print Page Previous Next Advertisements ”;
MVC Framework – Folders
MVC Framework – Folders ”; Previous Next Now that we have already created a sample MVC application, let us understand the folder structure of an MVC project. We will create new a MVC project to learn this. In your Visual Studio, open File → New → Project and select ASP.NET MVC Application. Name it as MVCFolderDemo. Click OK. In the next window, select Internet Application as the Project Template and click OK. This will create a sample MVC application as shown in the following screenshot. Note − Files present in this project are coming out of the default template that we have selected. These may change slightly as per different versions. Controllers Folder This folder will contain all the Controller classes. MVC requires the name of all the controller files to end with Controller. In our example, the Controllers folder contains two class files: AccountController and HomeController. Models Folder This folder will contain all the Model classes, which are used to work on application data. In our example, the Models folder contains AccountModels. You can open and look at the code in this file to see how the data model is created for managing accounts in our example. Views Folder This folder stores the HTML files related to application display and user interface. It contains one folder for each controller. In our example, you will see three sub-folders under Views, namely Account, Home and Shared which contains html files specific to that view area. App_Start Folder This folder contains all the files which are needed during the application load. For e.g., the RouteConfig file is used to route the incoming URL to the correct Controller and Action. Content Folder This folder contains all the static files, such as css, images, icons, etc. The Site.css file inside this folder is the default styling that the application applies. Scripts Folder This folder stores all the JS files in the project. By default, Visual Studio adds MVC, jQuery and other standard JS libraries. Print Page Previous Next Advertisements ”;
MVC Framework – Models
MVC Framework – Models ”; Previous Next The component ‘Model’ is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. Model classes can either be created manually or generated from database entities. We are going to see a lot of examples for manually creating Models in the coming chapters. Thus in this chapter, we will try the other option, i.e. generating from the database so that you have hands-on experience on both the methods. Create Database Entities Connect to SQL Server and create a new database. Now run the following queries to create new tables. CREATE TABLE [dbo].[Student]( [StudentID] INT IDENTITY (1,1) NOT NULL, [LastName] NVARCHAR (50) NULL, [FirstName] NVARCHAR (50) NULL, [EnrollmentDate] DATETIME NULL, PRIMARY KEY CLUSTERED ([StudentID] ASC) ) CREATE TABLE [dbo].[Course]( [CourseID] INT IDENTITY (1,1) NOT NULL, [Title] NVARCHAR (50) NULL, [Credits] INT NULL, PRIMARY KEY CLUSTERED ([CourseID] ASC) ) CREATE TABLE [dbo].[Enrollment]( [EnrollmentID] INT IDENTITY (1,1) NOT NULL, [Grade] DECIMAL(3,2) NULL, [CourseID] INT NOT NULL, [StudentID] INT NOT NULL, PRIMARY KEY CLUSTERED ([EnrollmentID] ASC), CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID]) REFERENCES [dbo].[Course]([CourseID]) ON DELETE CASCADE, CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student]([StudentID]) ON DELETE CASCADE ) Generate Models Using Database Entities After creating the database and setting up the tables, you can go ahead and create a new MVC Empty Application. Right-click on the Models folder in your project and select Add → New Item. Then, select ADO.NET Entity Data Model. In the next wizard, choose Generate From Database and click Next. Set the Connection to your SQL database. Select your database and click Test Connection. A screen similar to the following will follow. Click Next. Select Tables, Views, and Stored Procedures and Functions. Click Finish. You will see the Model View created as shown in the following screenshot. The above operations would automatically create a Model file for all the database entities. For example, the Student table that we created will result in a Model file Student.cs with the following code − namespace MvcModelExample.Models { using System; using System.Collections.Generic; public partial class Student { public Student() { this.Enrollments = new HashSet(); } public int StudentID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public Nullable EnrollmentDate { get; set; } public virtual ICollection Enrollments { get; set; } } } Print Page Previous Next Advertisements ”;