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›Action Methods, Parameterized action methods
    Enterprise Application DevelopmentTopic 25 of 37

    Action Methods, Parameterized action methods

    7 minread
    1,127words
    Intermediatelevel

    Action Methods in ASP.NET MVC

    In ASP.NET MVC, Action Methods are the heart of the controller. These methods are responsible for processing incoming HTTP requests, interacting with models to fetch or modify data, and returning a result, typically a view (HTML) that is rendered to the user.

    Action methods are typically public methods in a controller class that return an ActionResult. The ActionResult represents the outcome of the action, and there are different types of results that can be returned depending on what you want the application to do (return a view, redirect, return JSON data, etc.).


    1. Basic Action Method

    A basic action method doesn't accept any parameters and usually returns a ViewResult, which is the view that will be rendered.

    Example of a Basic Action Method:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();  // Returns the default view (Index.cshtml) to the user
        }
    }
    

    In this example:

    • The Index action method returns the Index view.

    The ActionResult returned here is a ViewResult by default.


    2. Action Methods Returning Different Result Types

    Action methods can return several different types of ActionResult, depending on the requirements. Common types of ActionResult include:

    ViewResult

    • Purpose: Renders a view (typically HTML) to the browser.
    • Example:
    public ActionResult About()
    {
        return View();  // Renders About.cshtml view
    }
    

    RedirectResult

    • Purpose: Redirects the user to a different URL or action.
    • Example:
    public ActionResult RedirectToAbout()
    {
        return RedirectToAction("About");  // Redirects to About action
    }
    

    JsonResult

    • Purpose: Returns data in JSON format (useful for AJAX calls).
    • Example:
    public JsonResult GetProduct(int id)
    {
        var product = productService.GetProductById(id);
        return Json(product, JsonRequestBehavior.AllowGet);  // Returns JSON data for AJAX requests
    }
    

    ContentResult

    • Purpose: Returns raw content (such as plain text or HTML).
    • Example:
    public ContentResult GetText()
    {
        return Content("Hello, World!");  // Returns plain text
    }
    

    RedirectToRouteResult

    • Purpose: Redirects to a specified route, which is helpful when you want to control the URL through routes.
    • Example:
    public RedirectToRouteResult RedirectToProductList()
    {
        return RedirectToRoute(new { controller = "Product", action = "List" });  // Redirect to a specific route
    }
    

    3. Parameterized Action Methods

    Parameterized action methods allow you to pass data from the URL (or the request) to the controller. This is particularly useful when you need to work with dynamic data, such as showing details for a specific product or handling form submissions with user input.

    The parameters passed to action methods can be query string parameters, route data, or form data.


    3.1. Passing Parameters via the URL (Route Data)

    ASP.NET MVC automatically binds values from the URL (route data) to action method parameters.

    For example, consider the following route:

    /Product/Details/5
    

    This route maps to an action method that takes an id parameter, like so:

    public class ProductController : Controller
    {
        public ActionResult Details(int id)
        {
            var product = productService.GetProductById(id);
            return View(product);  // Returns the product details view
        }
    }
    
    • In this case, the id parameter in the URL (which is 5 in the example) is automatically passed to the Details action method.

    3.2. Passing Parameters via Query String

    You can also pass parameters using the query string in the URL. The query string is usually written as key=value pairs.

    Example URL:

    /Product/Details?id=5
    

    Action method example:

    public ActionResult Details(int id)
    {
        var product = productService.GetProductById(id);
        return View(product);
    }
    

    In this case, the id parameter is retrieved from the query string (id=5).


    3.3. Using Multiple Parameters

    You can pass multiple parameters to an action method. The order of parameters in the URL or query string should match the order of parameters in the method signature.

    Example URL:

    /Product/Details/5/Red
    

    Action method:

    public ActionResult Details(int id, string color)
    {
        var product = productService.GetProductById(id);
        product.Color = color;
        return View(product);  // Passes the product with the selected color to the view
    }
    

    In this case:

    • id is passed as 5
    • color is passed as Red

    3.4. Optional Parameters

    ASP.NET MVC also allows you to define optional parameters in action methods. This can be useful when a parameter may or may not be provided in the URL or query string.

    Example URL:

    /Product/Details/5
    

    OR

    /Product/Details/5/Red
    

    Action method with optional parameter:

    public ActionResult Details(int id, string color = "Blue")
    {
        var product = productService.GetProductById(id);
        product.Color = color;  // Default color is Blue if not provided
        return View(product);
    }
    

    In this example, if the color parameter is not provided, it will default to "Blue", making the color parameter optional.


    3.5. Handling Invalid Parameters

    You can handle invalid or missing parameters by using model binding validation or applying custom logic inside the action method.

    For example, if a parameter is required, you can check its validity manually:

    public ActionResult Details(int id)
    {
        if (id <= 0)
        {
            // Redirect or return an error view if the parameter is invalid
            return RedirectToAction("Error");
        }
    
        var product = productService.GetProductById(id);
        return View(product);
    }
    

    In this example:

    • The method checks if the id is less than or equal to 0 and redirects to an error page if the parameter is invalid.

    4. Using Attributes for Parameter Binding

    In some cases, you might want to control how parameters are passed to action methods. For example, you can use [FromQuery] or [FromRoute] attributes to specify the source of the parameter (although this is typically more common in Web API controllers).

    For MVC, it’s standard to rely on URL or query string data, but using these attributes could give more flexibility in advanced scenarios.


    5. Action Method Overloading

    Action methods can be overloaded in ASP.NET MVC. However, overloading should be used cautiously, as it can make routing decisions ambiguous. For example, it can be unclear whether to map a request to an action with parameters or an action without parameters.

    Overloading example:

    public ActionResult Details()
    {
        return View("DetailsWithoutId");
    }
    
    public ActionResult Details(int id)
    {
        var product = productService.GetProductById(id);
        return View(product);  // Returns the product details view
    }
    

    In this case, if the URL is /Product/Details, the first method (without parameters) will be called, and if the URL is /Product/Details/5, the second method (with the id parameter) will be called.


    Conclusion

    Action Methods are the core components of ASP.NET MVC controllers that handle user requests and return appropriate results (such as views, redirects, or JSON data). These methods can accept parameters, either via URL route data, query strings, or form submissions, to dynamically process data and provide a personalized user experience.

    By using parameterized action methods, ASP.NET MVC provides a flexible way to design dynamic and data-driven web applications.

    Previous topic 24
    MVC application structure, Controllers overview
    Next topic 26
    Introduction to razor syntax

    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,127
      Code examples0
      DifficultyIntermediate