ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Mvc Architecture
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    7 min read
    Topic 24 of 37
    Topic Study Note Illustration
    24

    MVC application structure, Controllers overview

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development