MVC Framework – Introduction ”; Previous Next The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects. MVC Components Following are the components of MVC − Model The Model component corresponds to all the data-related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic-related data. For example, a Customer object will retrieve the customer information from the database, manipulate it and update it data back to the database or use it to render data. View The View component is used for all the UI logic of the application. For example, the Customer view will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with. Controller Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. For example, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. The same controller will be used to view the Customer data. ASP.NET MVC ASP.NET supports three major development models: Web Pages, Web Forms and MVC (Model View Controller). ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC applications which can be added as a template in Visual Studio. ASP.NET MVC Features ASP.NET MVC provides the following features − Ideal for developing complex but lightweight applications. Provides an extensible and pluggable framework, which can be easily replaced and customized. For example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other third-party view engines or even customize the existing ones. Utilizes the component-based design of the application by logically dividing it into Model, View, and Controller components. This enables the developers to manage the complexity of large-scale projects and work on individual components. MVC structure enhances the test-driven development and testability of the application, since all the components can be designed interface-based and tested using mock objects. Hence, ASP.NET MVC Framework is ideal for projects with large team of web developers. Supports all the existing vast ASP.NET functionalities, such as Authorization and Authentication, Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc. Does not use the concept of View State (which is present in ASP.NET). This helps in building applications, which are lightweight and gives full control to the developers. Thus, you can consider MVC Framework as a major framework built on top of ASP.NET providing a large set of added functionality focusing on component-based development and testing. Print Page Previous Next Advertisements ”;
Category: mvc Framework
MVC Framework – Layouts
MVC Framework – Layouts ”; Previous Next Layouts are used in MVC to provide a consistent look and feel on all the pages of our application. It is the same as defining the Master Pages but MVC provides some more functionalities. Create MVC Layouts Step 1 − Create a sample MVC application with Internet application as Template and create a Content folder in the root directory of the web application. Step 2 − Create a Style Sheet file named MyStyleSheet.css under the CONTENT folder. This CSS file will contain all the CSS classes necessary for a consistent web application page design. Step 3 − Create a Shared folder under the View folder. Step 4 − Create a MasterLayout.cshtml file under the Shared folder. The file MasterLayout.cshtml represents the layout of each page in the application. Right-click on the Shared folder in the Solution Explorer, then go to Add item and click View. Copy the following layout code. Layout Code <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “utf-8” /> <title>@ViewBag.Title – Tutorial Point</title> <link href = “~/favicon.ico” rel = “shortcut icon” type = “image/x-icon” /> <link rel = “stylesheet” href = “@Url.Content(“~/Content/MyStyleSheet.css”)” /> </head> <body> <header> <div class = “content-wrapper”> <div class = “float-left”> <p class = “site-title”> @Html.ActionLink(“Tutorial Point”, “Index”, “Home”) </p> </div> <div class = “float-right”> <nav> <ul id = “menu”> <li>@Html.ActionLink(“Home”, “Index”, “Home”)</li> <li>@Html.ActionLink(“About”, “About”, “Home”)</li> </ul> </nav> </div> </div> </header> <div id = “body”> @RenderSection(“featured”, required: false) <section class = “content-wrapper main-content clear-fix”> @RenderBody() </section> </div> <footer> <div class = “content-wrapper”> <div class = “float-left”> <p>© @DateTime.Now.Year – Tutorial Point</p> </div> </div> </footer> </body> </html> In this layout, we are using an HTML helper method and some other system-defined methods, hence let”s look at these methods one by one. Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path. Html.ActionLink() − This method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name. RenderSection() − Specifies the name of the section that we want to display at that location in the template. RenderBody() − Renders the actual body of the associated View. Step 5 − Finally, open the _ViewStart.cshtml file inside Views folder and add the following code − @{ Layout = “~/Views/Shared/_Layout.cshtml”; } If the file is not present, you can create the file with this name. Step 6 − Run the application now to see the modified home page. Print Page Previous Next Advertisements ”;
MVC Framework – Quick Guide
MVC Framework – Quick Guide ”; Previous Next MVC Framework – Introduction The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects. MVC Components Following are the components of MVC − Model The Model component corresponds to all the data-related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic-related data. For example, a Customer object will retrieve the customer information from the database, manipulate it and update it data back to the database or use it to render data. View The View component is used for all the UI logic of the application. For example, the Customer view will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with. Controller Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. For example, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. The same controller will be used to view the Customer data. ASP.NET MVC ASP.NET supports three major development models: Web Pages, Web Forms and MVC (Model View Controller). ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC applications which can be added as a template in Visual Studio. ASP.NET MVC Features ASP.NET MVC provides the following features − Ideal for developing complex but lightweight applications. Provides an extensible and pluggable framework, which can be easily replaced and customized. For example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other third-party view engines or even customize the existing ones. Utilizes the component-based design of the application by logically dividing it into Model, View, and Controller components. This enables the developers to manage the complexity of large-scale projects and work on individual components. MVC structure enhances the test-driven development and testability of the application, since all the components can be designed interface-based and tested using mock objects. Hence, ASP.NET MVC Framework is ideal for projects with large team of web developers. Supports all the existing vast ASP.NET functionalities, such as Authorization and Authentication, Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc. Does not use the concept of View State (which is present in ASP.NET). This helps in building applications, which are lightweight and gives full control to the developers. Thus, you can consider MVC Framework as a major framework built on top of ASP.NET providing a large set of added functionality focusing on component-based development and testing. MVC Framework – Architecture In the last chapter, we studied the high-level architecture flow of MVC Framework. Now let us take a look at how the execution of an MVC application takes place when there is a certain request from the client. The following diagram illustrates the flow. MVC Flow Diagram Flow Steps Step 1 − The client browser sends request to the MVC Application. Step 2 − Global.ascx receives this request and performs routing based on the URL of the incoming request using the RouteTable, RouteData, UrlRoutingModule and MvcRouteHandler objects. Step 3 − This routing operation calls the appropriate controller and executes it using the IControllerFactory object and MvcHandler object”s Execute method. Step 4 − The Controller processes the data using Model and invokes the appropriate method using ControllerActionInvoker object Step 5 − The processed Model is then passed to the View, which in turn renders the final output. MVC Framework – ASP.NET Forms MVC and ASP.NET Web Forms are inter-related yet different models of development, depending on the requirement of the application and other factors. At a high level, you can consider that MVC is an advanced and sophisticated web application framework designed with separation of concerns and testability in mind. Both the frameworks have their advantages and disadvantages depending on specific requirements. This concept can be visualized using the following diagram − MVC and ASP.NET Diagram Comparison Table MVC Framework – First Application Let us jump in and create our first MVC application using Views and Controllers. Once we have a small hands-on experience on how a basic MVC application works, we will learn all the individual components and concepts in the coming chapters. Create First MVC Application Step 1 − Start your Visual Studio and select File → New → Project. Select Web → ASP.NET MVC Web Application and name this project as FirstMVCApplicatio. Select the Location as C:MVC. Click OK. Step 2 − This will open the Project Template option. Select Empty template and View Engine as Razor. Click OK. Now, Visual Studio will create our first MVC project as shown in the following screenshot. Step 3 − Now we will create the first Controller in our application. Controllers are just simple C# classes, which contains multiple public methods, known as action methods. To add a new Controller, right-click the Controllers folder in our project and select Add → Controller. Name the Controller as HomeController and click Add. This will create a class file HomeController.cs under the Controllers folder with the following default code. using System; using System.Web.Mvc; namespace FirstMVCApplication.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } } } The above code basically defines a public method Index inside our HomeController and returns a ViewResult
MVC Framework – Action Filters ”; Previous Next In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc. However, many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller”s action methods. Types of Filters ASP.NET MVC framework supports the following action filters − Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter. Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions. Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser. Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors. Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time. Action Filters Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields. ASP.NET MVC provides the following action filters − Output Cache − This action filter caches the output of a controller action for a specified amount of time. Handle Error − This action filter handles errors raised when a controller action executes. Authorize − This action filter enables you to restrict access to a particular user or role. Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.) Output Cache Example − Specifies the return value to be cached for 10 seconds. public class ActionFilterDemoController : Controller { [HttpGet] OutputCache(Duration = 10)] public string Index() { return DateTime.Now.ToString(“T”); } } Handle Error Example − Redirects application to a custom error page when an error is triggered by the controller. [HandleError] public class ActionFilterDemoController : Controller { public ActionResult Index() { throw new NullReferenceException(); } public ActionResult About() { return View(); } } With the above code, if any error happens during the action execution, it will find a view named Error in the Views folder and render that page to the user. Authorize Example − Allowing only authorized users to log in the application. public class ActionFilterDemoController: Controller { [Authorize] public ActionResult Index() { ViewBag.Message = “This can be viewed only by authenticated users only”; return View(); } [Authorize(Roles=”admin”)] public ActionResult AdminIndex() { ViewBag.Message = “This can be viewed only by users in Admin role only”; return View(); } } With the above code, if you would try to access the application without logging in, it will throw an error similar to the one shown in the following screenshot. Print Page Previous Next Advertisements ”;
MVC Framework – Routing Engine ”; Previous Next ASP.NET MVC Routing enables the use of URLs that are descriptive of the user actions and are more easily understood by the users. At the same time, Routing can be used to hide data which is not intended to be shown to the final user. For example, in an application that does not use routing, the user would be shown the URL as http://myapplication/Users.aspx?id=1 which would correspond to the file Users.aspx inside myapplication path and sending ID as 1, Generally, we would not like to show such file names to our final user. To handle MVC URLs, ASP.NET platform uses the routing system, which lets you create any pattern of URLs you desire, and express them in a clear and concise manner. Each route in MVC contains a specific URL pattern. This URL pattern is compared to the incoming request URL and if the URL matches this pattern, it is used by the routing engine to further process the request. MVC Routing URL Format To understand the MVC routing, consider the following URL − http://servername/Products/Phones In the above URL, Products is the first segment and Phone is the second segment which can be expressed in the following format − {controller}/{action} The MVC framework automatically considers the first segment as the Controller name and the second segment as one of the actions inside that Controller. Note − If the name of your Controller is ProductsController, you would only mention Products in the routing URL. The MVC framework automatically understands the Controller suffix. Create a Simple Route Routes are defined in the RouteConfig.cs file which is present under the App_Start project folder. You will see the following code inside this file − public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”); routes.MapRoute( name: “Default”, url: “{controller}/{action}/{id}”, defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional } ); } } This RegisterRoutes method is called by the Global.ascx when the application is started. The Application_Start method under Global.ascx calls this MapRoute function which sets the default Controller and its action (method inside the Controller class). To modify the above default mapping as per our example, change the following line of code − defaults: new { controller = “Products”, action = “Phones”, id = UrlParameter.Optional } This setting will pick the ProductsController and call the Phone method inside that. Similarly, if you have another method such as Electronics inside ProductsController, the URL for it would be − http://servername/Products/Electronics Print Page Previous Next Advertisements ”;
MVC Framework – Architecture
MVC Framework – Architecture ”; Previous Next In the last chapter, we studied the high-level architecture flow of MVC Framework. Now let us take a look at how the execution of an MVC application takes place when there is a certain request from the client. The following diagram illustrates the flow. MVC Flow Diagram Flow Steps Step 1 − The client browser sends request to the MVC Application. Step 2 − Global.ascx receives this request and performs routing based on the URL of the incoming request using the RouteTable, RouteData, UrlRoutingModule and MvcRouteHandler objects. Step 3 − This routing operation calls the appropriate controller and executes it using the IControllerFactory object and MvcHandler object”s Execute method. Step 4 − The Controller processes the data using Model and invokes the appropriate method using ControllerActionInvoker object Step 5 − The processed Model is then passed to the View, which in turn renders the final output. Print Page Previous Next Advertisements ”;
MVC Framework – Views
MVC Framework – Views ”; Previous Next As seen in the initial introductory chapters, View is the component involved with the application”s User Interface. These Views are generally bind from the model data and have extensions such as html, aspx, cshtml, vbhtml, etc. In our First MVC Application, we had used Views with Controller to display data to the final user. For rendering these static and dynamic content to the browser, MVC Framework utilizes View Engines. View Engines are basically markup syntax implementation, which are responsible for rendering the final HTML to the browser. MVC Framework comes with two built-in view engines − Razor Engine − Razor is a markup syntax that enables the server side C# or VB code into web pages. This server side code can be used to create dynamic content when the web page is being loaded. Razor is an advanced engine as compared to ASPX engine and was launched in the later versions of MVC. ASPX Engine − ASPX or the Web Forms engine is the default view engine that is included in the MVC Framework since the beginning. Writing a code with this engine is similar to writing a code in ASP.NET Web Forms. Following are small code snippets comparing both Razor and ASPX engine. Razor @Html.ActionLink(“Create New”, “UserAdd”) ASPX <% Html.ActionLink(“SignUp”, “SignUp”) %> Out of these two, Razor is an advanced View Engine as it comes with compact syntax, test driven development approaches, and better security features. We will use Razor engine in all our examples since it is the most dominantly used View engine. These View Engines can be coded and implemented in following two types − Strongly typed Dynamic typed These approaches are similar to early-binding and late-binding respectively in which the models will be bind to the View strongly or dynamically. Strongly Typed Views To understand this concept, let us create a sample MVC application (follow the steps in the previous chapters) and add a Controller class file named ViewDemoController. Now, copy the following code in the controller file − using System.Collections.Generic; using System.Web.Mvc; namespace ViewsInMVC.Controllers { public class ViewDemoController : Controller { public class Blog { public string Name; public string URL; } private readonly List topBlogs = new List { new Blog { Name = “Joe Delage”, URL = “http://tutorialspoint/joe/”}, new Blog {Name = “Mark Dsouza”, URL = “http://tutorialspoint/mark”}, new Blog {Name = “Michael Shawn”, URL = “http://tutorialspoint/michael”} }; public ActionResult StonglyTypedIndex() { return View(topBlogs); } public ActionResult IndexNotStonglyTyped() { return View(topBlogs); } } } In the above code, we have two action methods defined: StronglyTypedIndex and IndexNotStonglyTyped. We will now add Views for these action methods. Right-click on StonglyTypedIndex action method and click Add View. In the next window, check the ”Create a strongly-typed view” checkbox. This will also enable the Model Class and Scaffold template options. Select List from Scaffold Template option. Click Add. A View file similar to the following screenshot will be created. As you can note, it has included the ViewDemoController”s Blog model class at the top. You will also be able to use IntelliSense in your code with this approach. Dynamic Typed Views To create dynamic typed views, right-click the IndexNotStonglyTyped action and click Add View. This time, do not select the ”Create a strongly-typed view” checkbox. The resulting view will have the following code − @model dynamic @{ ViewBag.Title = “IndexNotStonglyTyped”; } <h2>Index Not Stongly Typed</h2> <p> <ul> @foreach (var blog in Model) { <li> <a href = “@blog.URL”>@blog.Name</a> </li> } </ul> </p> As you can see in the above code, this time it did not add the Blog model to the View as in the previous case. Also, you would not be able to use IntelliSense this time because this time the binding will be done at run-time. Strongly typed Views is considered as a better approach since we already know what data is being passed as the Model unlike dynamic typed Views in which the data gets bind at runtime and may lead to runtime errors, if something changes in the linked model. Print Page Previous Next Advertisements ”;
MVC Framework – First Application ”; Previous Next Let us jump in and create our first MVC application using Views and Controllers. Once we have a small hands-on experience on how a basic MVC application works, we will learn all the individual components and concepts in the coming chapters. Create First MVC Application Step 1 − Start your Visual Studio and select File → New → Project. Select Web → ASP.NET MVC Web Application and name this project as FirstMVCApplicatio. Select the Location as C:MVC. Click OK. Step 2 − This will open the Project Template option. Select Empty template and View Engine as Razor. Click OK. Now, Visual Studio will create our first MVC project as shown in the following screenshot. Step 3 − Now we will create the first Controller in our application. Controllers are just simple C# classes, which contains multiple public methods, known as action methods. To add a new Controller, right-click the Controllers folder in our project and select Add → Controller. Name the Controller as HomeController and click Add. This will create a class file HomeController.cs under the Controllers folder with the following default code. using System; using System.Web.Mvc; namespace FirstMVCApplication.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } } } The above code basically defines a public method Index inside our HomeController and returns a ViewResult object. In the next steps, we will learn how to return a View using the ViewResult object. Step 4 − Now we will add a new View to our Home Controller. To add a new View, rightclick view folder and click Add → View. Step 5 − Name the new View as Index and View Engine as Razor (SCHTML). Click Add. This will add a new cshtml file inside Views/Home folder with the following code − @{ Layout = null; } <html> <head> <meta name = “viewport” content = “width = device-width” /> <title>Index</title> </head> <body> <div> </div> </body> </html> Step 6 − Modify the above View”s body content with the following code − <body> <div> Welcome to My First MVC Application (<b>From Index View</b>) </div> </body> Step 7 − Now run the application. This will give you the following output in the browser. This output is rendered based on the content in our View file. The application first calls the Controller which in turn calls this View and produces the output. In Step 7, the output we received was based on the content of our View file and had no interaction with the Controller. Moving a step forward, we will now create a small example to display a Welcome message with the current time using an interaction of View and Controller. Step 8 − MVC uses the ViewBag object to pass data between Controller and View. Open the HomeController.cs and edit the Index function to the following code. public ViewResult Index() { int hour = DateTime.Now.Hour; ViewBag.Greeting = hour < 12 ? “Good Morning. Time is” + DateTime.Now.ToShortTimeString() : “Good Afternoon. Time is ” + DateTime.Now.ToShortTimeString(); return View(); } In the above code, we set the value of the Greeting attribute of the ViewBag object. The code checks the current hour and returns the Good Morning/Afternoon message accordingly using return View() statement. Note that here Greeting is just an example attribute that we have used with ViewBag object. You can use any other attribute name in place of Greeting. Step 9 − Open the Index.cshtml and copy the following code in the body section. <body> <div> @ViewBag.Greeting (<b>From Index View</b>) </div> </body> In the above code, we are accessing the value of Greeting attribute of the ViewBag object using @ (which would be set from the Controller). Step 10 − Now run the application again. This time our code will run the Controller first, set the ViewBag and then render it using the View code. Following will be the output. Print Page Previous Next Advertisements ”;
MVC Framework – Ajax Support
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 ”;
Advanced Example
MVC Framework – Advanced Example ”; Previous Next In the first chapter, we learnt how Controllers and Views interact in MVC. In this tutorial, we are going to take a step forward and learn how to use Models and create an advanced application to create, edit, delete. and view the list of users in our application. Create an Advanced MVC Application Step 1 − Select File → New → Project → ASP.NET MVC Web Application. Name it as AdvancedMVCApplication. Click Ok. In the next window, select Template as Internet Application and View Engine as Razor. Observe that we are using a template this time instead of an Empty application. This will create a new solution project as shown in the following screenshot. Since we are using the default ASP.NET theme, it comes with sample Views, Controllers, Models and other files. Step 2 − Build the solution and run the application to see its default output as shown in the following screenshot. Step 3 − Add a new model which will define the structure of users data. Right-click on Models folder and click Add → Class. Name this as UserModel and click Add. Step 4 − Copy the following code in the newly created UserModel.cs. using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc.Html; namespace AdvancedMVCApplication.Models { public class UserModels { [Required] public int Id { get; set; } [DisplayName(“First Name”)] [Required(ErrorMessage = “First name is required”)] public string FirstName { get; set; } [Required] public string LastName { get; set; } public string Address { get; set; } [Required] [StringLength(50)] public string Email { get; set; } [DataType(DataType.Date)] public DateTime DOB { get; set; } [Range(100,1000000)] public decimal Salary { get; set; } } } In the above code, we have specified all the parameters that the User model has, their data types and validations such as required fields and length. Now that we have our User Model ready to hold the data, we will create a class file Users.cs, which will contain methods for viewing users, adding, editing, and deleting users. Step 5 − Right-click on Models and click Add → Class. Name it as Users. This will create users.cs class inside Models. Copy the following code in the users.cs class. using System; using System.Collections.Generic; using System.EnterpriseServices; namespace AdvancedMVCApplication.Models { public class Users { public List UserList = new List(); //action to get user details public UserModels GetUser(int id) { UserModels usrMdl = null; foreach (UserModels um in UserList) if (um.Id == id) usrMdl = um; return usrMdl; } //action to create new user public void CreateUser(UserModels userModel) { UserList.Add(userModel); } //action to udpate existing user public void UpdateUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { usrlst.Address = userModel.Address; usrlst.DOB = userModel.DOB; usrlst.Email = userModel.Email; usrlst.FirstName = userModel.FirstName; usrlst.LastName = userModel.LastName; usrlst.Salary = userModel.Salary; break; } } } //action to delete exising user public void DeleteUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { UserList.Remove(usrlst); break; } } } } } Once we have our UserModel.cs and Users.cs, we will add Views to our model for viewing users, adding, editing and deleting users. First let us create a View to create a user. Step 6 − Right-click on the Views folder and click Add → View. Step 7 − In the next window, select the View Name as UserAdd, View Engine as Razor and select the Create a strongly-typed view checkbox. Step 8 − Click Add. This will create the following CSHML code by default as shown below − @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = “UserAdd”; } <h2>UserAdd</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> <div class = “editor-label”> @Html.LabelFor(model => model.FirstName) </div> <div class = “editor-field”> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class = “editor-label”> @Html.LabelFor(model => model.LastName) </div> <div class = “editor-field”> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Address) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Email) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class = “editor-label”> @Html.LabelFor(model => model.DOB) </div> <div class = “editor-field”> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Salary) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type = “submit” value = “Create” /> </p> </fieldset> } <div> @Html.ActionLink(“Back to List”, “Index”) </div> @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) } As you can see, this view contains view details of all the attributes of the fields including their validation messages, labels, etc. This View will look like the following in our final application. Similar to UserAdd, now we will add four more Views given below with the given code − Index.cshtml This View will display all the users present in our system on the Index page. @model IEnumerable<AdvancedMVCApplication.Models.UserModels> @{ ViewBag.Title = “Index”; } <h2>Index</h2> <p> @Html.ActionLink(“Create New”, “UserAdd”) </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.Email) </th> <th> @Html.DisplayNameFor(model => model.DOB) </th> <th> @Html.DisplayNameFor(model => model.Salary) </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.Address) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.DOB) </td> <td> @Html.DisplayFor(modelItem => item.Salary) </td> <td> @Html.ActionLink(“Edit”, “Edit”, new { id = item.Id }) | @Html.ActionLink(“Details”, “Details”, new { id = item.Id }) | @Html.ActionLink(“Delete”, “Delete”, new { id = item.Id }) </td> </tr> } </table> This View will look like the following in our final application. Details.cshtml This View will display the details of a specific user when we click on the user record. @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = “Details”; } <h2>Details</h2> <fieldset> <legend>UserModels</legend> <div class = “display-label”> @Html.DisplayNameFor(model => model.FirstName) </div> <div class = “display-field”> @Html.DisplayFor(model => model.FirstName) </div> <div class = “display-label”> @Html.DisplayNameFor(model => model.LastName) </div> <div class = “display-field”> @Html.DisplayFor(model => model.LastName) </div> <div class =