MVC id Value always null

Viewed 797

I am new in ASP.NET MVC. One of my first task I would like to do is passing a parameter to the HomeController.

To accomplish this I modified default Index method to:

public string Index(string strParam)
{
    return "Param: " + strParam;
}

I also pass my parameter via url as:

https://localhost:44308/home/index/test

but the parameter strParam is always null. How can I pass some parameters to my method using url?

My route config is default:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
 }
5 Answers

You should name the parameter in the Index method id, as per the route definition. Otherwise, if you don't want to change it, add an HttpGet attribute such as:

[HttpGet]
[Route("[action]/{strParam}")

As alternative, in your route its defined as id. If you name your paramater as such, it will also work.

public string Index(string id)

then try the following:

 [Route("[controller]/[action]")]
 [ApiController]
 public class TestController : Controller
  {       
    [HttpGet("{value}")]
    [Route("/Test/Index")]
    public string Index(string value)
    {
        return "Hello " + value;
    }

in my startup -> Configure goes below:

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllerRoute(
   name: "default1",
   pattern: "{controller}/{action}");
});

http://localhost:5001/test/index/World

Output: Hello World

have you try the following:

  [HttpGet("{strParam}")]
  [Route("/Home/Index")]

  public string Index(string strParam)
Related