Same action method and different parameters in .NET core

Sheonarayan
Posted by in ASP.NET Core category on for Intermediate level | Points: 250 | Views : 21770 red flag
Rating: 4.8 out of 5  
 5 vote(s)

In this article, we will learn how to use same action method name with different parameters and return different views in .NET Core.
Recommendation
Read Creating Custom Tag Helper in ASP.NET Core before this article.

Introduction

In many requirements you may not want to have an action method name in the URL in ASP.NET Core applications. You just want to list the items in the Index page and show the specific items by passing id without having action method name in the URL like below.
  1. List of items url - http://localhost:44304/Shares
  2. Show specific items url - http://localhost:44304/Shares/2/what-is-minda-industries
Notice the 2nd url, there is no action method. Here 
  1. Shares is the action name
  2. 2 is the item id
  3. what-is-mind-industries - is the title of item
In normal scenarios, this is not possible however we will learn how to do above in ASP.NET Core.

Modify Startup.cs routes

Look at the 1st MapRoute, I have created a new MapRoute with "Shares" as explicit word in the URL. The 2nd MapRoute is default. When a URL that starts with /Shares/{with a digit}/{and with a title} is requested, the 1st MapRoute executes otherwise 2nd MapRoutes executes.

app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "Shares",
                template: "Shares/{id}/{title}",
                defaults: new { controller = "Shares", action = "Index" });

                routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}"
            );

Create a custom attribute

Now, create a custom attribute named RequiredParameter that inherits ActionMethodSelectorAttribute.

In below code snippet, we have a property named ValueName. In the constructor, we its property that is set when this custom attribute is used.

We also need to override IsValidForRequest method. Here we are checking if the requested url contains the route parameter we are passing. Based on this, it returns true or false.

using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;

public class RequiredParameterAttribute : ActionMethodSelectorAttribute
    {
        public RequiredParameterAttribute(string valueName)
        {
            ValueName = valueName;
        }
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            var isTrue = routeContext.RouteData.Values[ValueName] != null;
            return isTrue;
        }
        public string ValueName { get; private set; }
    }

If this method returns true, the action method that uses this attribute executes.

Using custom attribute in the action method

In below code snippet, notice that we two method with the same name but different parameters. Notice that both method are HttpGet method (default, if you do not specify method type, its HttpGet).

In the 2nd method, we are using RequiredParameter custom attribute that we have created in the above code snippet. We are passing "id" as parameter to this attribute.

// GET: Forums
        public async Task<IActionResult> Index()
        {
            return View(await _context.Forums.ToListAsync());
        }

        [RequiredParameter("id")]
        public async Task<IActionResult> Index(int id, string title)
        {
            return View("IndexList", await _context.Forums.ToListAsync());
        }

Now when we request 
  • http://localhost:44304/Shares - as the URL doesn't contains the id parameter so the 1st method executes. This intern return "Index" view.

  • http://localhost:44304/Shares/2/what-is-minda-industries - as the URL contains id value as 2 and title is what-is-minda-industries so the custom attribute returns true and this method executes and returns "IndexList" view.

Conclusion

The use of Custom attributes are very vast and it can be used in many scenarios, this is one of the use of custom attribute that help us making the URL look nice, small and easily readable.

Hope you found this articles useful, do write your feedback or comments. Thanks for reading.
Recommendation
Read 6 Steps to host ASP.NET MVC/Core application on server after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Pritambhatta on: 10/10/2019 | Points: 25
Great Information was very useful for me..
Posted by: Edgefindings on: 10/31/2019 | Points: 25
Great. Thanks for sharing this! :-)

Login to post response

Comment using Facebook(Author doesn't get notification)