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 Routing
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
    5 min read
    Topic 37 of 37
    Topic Study Note Illustration
    37

    MVC routing

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

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

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    922words
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development