MVC Controller Action string parameter always null

Dan 41 Reputation points
2021-05-11T02:48:38.687+00:00

Hi,

I've created an MVC web app using .NET Core 3.1. In the startup.cs I added the following route (before the default route):
endpoints.MapControllerRoute(
name: "getById",
pattern: "{controller}/{ equityID:alpha}",
defaults: new { controller = "Home", action = "Index",equityID = "CSCO" });

and in the stock controller I have the following action method:

        public async Task<ActionResult> Index([FromRoute(Name = "equityID")] string equityID)
{        {

            if (string.IsNullOrEmpty(equityID))
            { throw new ArgumentNullException("The equity ID is invalid - null or empty"); }

            var client = new IntrinioClient();
            var result = await client.GetRealtimePrice(equityID);
            var model = new StockViewModel() { Quote = result };

}
            return View("~/Views/Stock/Index.cshtml", model);
        }

The issue I'm having is that the equityID passed to the (ndex() action is always null. I can only get it to work by adding equityID = "CSCO" in the defaults of the route definition (but obviously that is not a viable solution). Have I missed something in the setup of the route or elsewhere? Any help would be very appreciated.

Thanks in Advance,
Dan

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,134 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,061 Reputation points
    2021-05-11T03:31:07.537+00:00

    Hi @Dan ,

    Change your route template like below, and the request url should be https://localhost:portNumber/Home/Index/YourequityID :

    endpoints.MapControllerRoute(  
        name: "getById",  
        pattern: "{controller}/{action}/{equityID:alpha}");  
    

    Note:
    Your providing code contains empty space( pattern: "{controller}/{ equityID:alpha}",
    ), be sure there is no empty space before equityID:alpha.


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Rena


0 additional answers

Sort by: Most helpful