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 Action Methods
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 25 of 37
    Topic Study Note Illustration
    25

    Action Methods, Parameterized action methods

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

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

    Click on Show Past Papers to load available exam papers.

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

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development