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 routing
    Enterprise Application DevelopmentTopic 37 of 37

    MVC routing

    5 minread
    922words
    Intermediatelevel

    MVC Routing in ASP.NET Core

    In ASP.NET Core MVC, routing is the process that determines which controller and action should handle an incoming HTTP request. When a user sends a request (such as navigating to a URL), the MVC routing system maps the URL to a corresponding controller and action method. The routing system defines how the request should be processed and where the response should come from.

    Basic Concepts of MVC Routing:

    1. Route: A URL pattern that is used to match incoming HTTP requests to the corresponding controller and action.
    2. Controller: A class in MVC that handles the logic for processing requests.
    3. Action: A method within the controller that handles a specific HTTP request.

    How Routing Works in MVC:

    Routing works by matching a URL pattern to a route template that corresponds to a controller and an action. The default routing convention in ASP.NET Core MVC is defined as follows:

    • URL format: /Controller/Action/Parameter

    For example:

    • https://example.com/Books/Details/1

    In this example:

    • Books is the Controller.
    • Details is the Action.
    • 1 is the parameter (in this case, it could be the book's ID).

    Default Routing in ASP.NET Core MVC

    In an ASP.NET Core MVC application, routes are typically defined in the Startup.cs file in the Configure method, using the UseEndpoints method.

    By default, ASP.NET Core uses the following pattern for routing:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    
    • controller=Home: Specifies that if no controller is provided in the URL, it will default to the HomeController.
    • action=Index: If no action is provided, it will default to the Index action.
    • {id?}: This represents an optional parameter (often an ID) that might be passed to the action. The ? indicates that the id parameter is optional.

    Examples of MVC Routing

    1. Basic Route Example:

    Given the default routing configuration:

    • URL: https://localhost:5000/Books/Details/5
      • Controller: BooksController
      • Action: Details
      • Parameter: id = 5

    The BooksController will handle the request, and the Details action will receive the id parameter, which is 5.

    public class BooksController : Controller
    {
        public IActionResult Details(int id)
        {
            // Fetch and return the book with the specified id
            var book = _bookService.GetBookById(id);
            return View(book);
        }
    }
    

    2. Route with Optional Parameter:

    You can create routes with optional parameters.

    • URL: https://localhost:5000/Books/Details/5

      • If the id is provided, it will call the Details action with the id.
    • URL: https://localhost:5000/Books/Details

      • If the id is not provided, it will call the Details action without the id.

    The route template in the Configure method:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    
    • {id?} makes the id parameter optional.

    Customizing Routes

    While the default route convention works for most cases, you may want to define custom routes to achieve cleaner, more descriptive URLs.

    Example 1: Custom Route with a Named Parameter

    Let's say you want to create a custom route for searching books by title:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "search",
            pattern: "Books/Search/{title}",
            defaults: new { controller = "Books", action = "Search" });
    });
    

    Now, the URL pattern Books/Search/{title} will map to the Search action in BooksController, where title is a parameter.

    • URL: https://localhost:5000/Books/Search/CSharp
      • Controller: BooksController
      • Action: Search
      • Parameter: title = CSharp
    public class BooksController : Controller
    {
        public IActionResult Search(string title)
        {
            var books = _bookService.SearchBooksByTitle(title);
            return View(books);
        }
    }
    

    Example 2: Custom Route with Constraints

    You can also add constraints to route parameters. For instance, let's define a route that only matches if the id is a number:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "idConstraint",
            pattern: "Books/Details/{id:int}",
            defaults: new { controller = "Books", action = "Details" });
    });
    

    In this case, the route will only match if the id is an integer. If a non-integer is provided (e.g., Books/Details/abc), the route will not match, and an error will be returned.


    Route Parameters in Action Methods

    When defining actions in your controllers, the parameters in the URL (such as id) are automatically mapped to the method parameters in the action method.

    For example, if you define the following route in Configure:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    

    And in your controller, you define the following action:

    public class BooksController : Controller
    {
        public IActionResult Details(int id)
        {
            var book = _bookService.GetBookById(id);
            return View(book);
        }
    }
    

    When the URL Books/Details/5 is requested, the id parameter in the URL (5) will automatically be passed to the Details action method.


    Attribute Routing

    Attribute routing provides a way to define routes directly on controller actions using attributes. This method is more flexible and allows for greater control over route definitions.

    Example of Attribute Routing:

    public class BooksController : Controller
    {
        [Route("Books/Details/{id}")]
        public IActionResult Details(int id)
        {
            var book = _bookService.GetBookById(id);
            return View(book);
        }
    
        [Route("Books/Search/{title}")]
        public IActionResult Search(string title)
        {
            var books = _bookService.SearchBooksByTitle(title);
            return View(books);
        }
    }
    

    In this case:

    • Books/Details/{id} will map to the Details action.
    • Books/Search/{title} will map to the Search action.

    Conclusion

    Routing in ASP.NET Core MVC is the mechanism that maps URLs to specific controllers and actions. By default, routing follows a pattern of {controller}/{action}/{id}, but you can customize routes to match your application's needs using attribute routing or custom route templates. MVC routing enables flexible and clean URL designs that make it easier for users and developers to interact with your application.

    Previous topic 36
    Example of web API using CRUD Example

    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 time5 min
      Word count922
      Code examples0
      DifficultyIntermediate