ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›MVC application structure, Controllers overview
    Enterprise Application DevelopmentTopic 24 of 37

    MVC application structure, Controllers overview

    7 minread
    1,181words
    Intermediatelevel

    MVC Application Structure

    In ASP.NET MVC, an application follows the Model-View-Controller (MVC) design pattern, which promotes separation of concerns and helps organize code for better maintainability and scalability. An MVC application typically has a well-defined structure, which separates different components into specific folders and files for clarity.

    Here’s an overview of the structure and purpose of the key components in an ASP.NET MVC application:


    1. MVC Application Folders and Files

    1.1. Models

    • Purpose: The Model represents the application's data, business logic, and rules. Models are typically C# classes that define the structure of data and interact with the database.
    • Location: The Models folder.

    Example:

    namespace MyApp.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal Price { get; set; }
        }
    }
    

    1.2. Views

    • Purpose: The View is responsible for rendering the user interface (UI). Views are typically Razor files (.cshtml) that contain HTML and C# code to dynamically generate content.

    • Location: The Views folder.

      • Inside Views, there is a subfolder for each Controller. For example, the ProductController would have a Views/Product folder containing views for displaying, editing, etc.

    Example:

    @model MyApp.Models.Product
    
    <h2>@Model.Name</h2>
    <p>Price: @Model.Price</p>
    

    1.3. Controllers

    • Purpose: The Controller is the intermediary between the Model and the View. It handles incoming requests, processes data (using models), and returns views (UI) with data to be displayed to the user.
    • Location: The Controllers folder.

    Example:

    namespace MyApp.Controllers
    {
        public class ProductController : Controller
        {
            // Action method to display a product
            public ActionResult Details(int id)
            {
                var product = productService.GetProductById(id);  // Fetch product from the service
                return View(product);  // Pass product data to the view
            }
        }
    }
    

    1.4. Views/Shared

    • Purpose: The Shared folder under Views contains views that are shared across multiple controllers (e.g., header, footer, layout).
    • Location: Views/Shared

    Example:

    @* _Layout.cshtml *@
    <!DOCTYPE html>
    <html>
    <head>
        <title>@ViewBag.Title</title>
    </head>
    <body>
        <header>
            <h1>Welcome to MyApp</h1>
        </header>
        @RenderBody()  <!-- Where the view content will go -->
        <footer>© 2025 MyApp</footer>
    </body>
    </html>
    

    1.5. App_Start

    • Purpose: Contains configuration files for the application, such as routing, authentication, and global settings.
    • Location: App_Start folder.

    Example: RouteConfig.cs inside App_Start sets up routing for the application.

    namespace MyApp.App_Start
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }
        }
    }
    

    1.6. Web.config

    • Purpose: Configuration file for settings like database connection strings, authentication, custom errors, etc.
    • Location: The root folder.

    1.7. Scripts and Content

    • Purpose:
      • The Scripts folder contains JavaScript files.
      • The Content folder contains static resources like CSS files and images.

    2. Controllers Overview

    In the MVC pattern, Controllers are responsible for handling user input and interacting with models to fetch or update data. The controller then decides which view to display to the user and passes the data to that view.

    Controller Structure

    A controller is typically a C# class that inherits from the Controller base class provided by ASP.NET MVC. Each action within the controller corresponds to a user request and returns an appropriate result (usually a view or redirect).


    Key Concepts in Controllers

    2.1. Action Methods

    • Action methods are public methods within a controller that handle requests. Each action method is responsible for processing a request and returning an ActionResult (e.g., a view, redirect, or JSON response).

    Example of action methods:

    public class ProductController : Controller
    {
        // Action to show product details
        public ActionResult Details(int id)
        {
            var product = productService.GetProductById(id);  // Assume productService fetches data from a database
            return View(product);  // Returns the product data to the view
        }
    
        // Action to display a list of products
        public ActionResult Index()
        {
            var products = productService.GetAllProducts();
            return View(products);  // Pass products to the view
        }
    }
    

    In the above example:

    • Details(int id): Displays the details of a single product based on the provided id.
    • Index(): Displays a list of all products.

    2.2. Routing and Controller Action Mapping

    Routing determines how URL patterns map to controller actions. ASP.NET MVC uses the RouteConfig.cs file to define how URL patterns should be matched to controller actions.

    For example, the URL http://example.com/Product/Details/1 would be routed to the ProductController and invoke the Details action with the id = 1.

    The default routing rule in the RouteConfig.cs file is:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    This means:

    • {controller} corresponds to the controller name (e.g., Product).
    • {action} corresponds to the action method (e.g., Details).
    • {id} corresponds to the optional parameter for the action (e.g., 1).

    2.3. Return Types: ActionResult

    The ActionResult class is the base class for all results returned by action methods. Some common derived types of ActionResult are:

    • ViewResult: Returns a view (HTML page).
    • RedirectResult: Redirects the user to another action or URL.
    • JsonResult: Returns data in JSON format (useful for AJAX requests).
    • PartialViewResult: Returns a partial view (HTML content) without reloading the entire page.
    • ContentResult: Returns raw content (like a text string).

    Example:

    public ActionResult RedirectToHome()
    {
        return RedirectToAction("Index", "Home");  // Redirects to Home/Index
    }
    
    public JsonResult GetProductData(int id)
    {
        var product = productService.GetProductById(id);
        return Json(product, JsonRequestBehavior.AllowGet);  // Returns product data as JSON
    }
    

    2.4. Passing Data from Controller to View

    Data is passed from a controller to a view in the following ways:

    1. ViewData: A dictionary used to pass data between the controller and the view.

      public ActionResult Details(int id)
      {
          var product = productService.GetProductById(id);
          ViewData["Product"] = product;  // Passing data to the view using ViewData
          return View();
      }
      
    2. ViewBag: A dynamic object used to pass data to the view.

      public ActionResult Details(int id)
      {
          var product = productService.GetProductById(id);
          ViewBag.Product = product;  // Passing data to the view using ViewBag
          return View();
      }
      
    3. Strongly Typed Models: Pass a model directly to the view, ensuring type safety.

      public ActionResult Details(int id)
      {
          var product = productService.GetProductById(id);
          return View(product);  // Passing strongly typed model to the view
      }
      

    Conclusion

    The MVC architecture in ASP.NET MVC provides a clean separation of concerns by dividing the application into Models, Views, and Controllers. The Controllers play a crucial role in managing user requests, interacting with the models, and returning views or other results.

    By using controllers effectively, you can keep the logic of processing requests separate from the UI, making the application more maintainable, testable, and scalable.

    Previous topic 23
    Introduction to ASP.NET MVC
    Next topic 25
    Action Methods, Parameterized action methods

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,181
      Code examples0
      DifficultyIntermediate