Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MCV: Index action with optional string parameter

I would like to have an Index action with an optional string parameter. I'm unable to make it work.

I need the following routes:

http://mysite/download
http://mysite/download/4.1.54.28

The first route will send a null model to the Index view, and the second one will send an string with the version number.

How can I define the route and the controller?

This is my route definition:

routes.MapRoute(
    name: "Download",
    url: "Download/{version}",
    defaults: new { controller = "Download", action = "Index", version = UrlParameter.Optional }
);

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

And this is the controller:

    public ActionResult Index(string version)
    {
        return View(version);
    }

Why does this not work? I'm not an expert in ASP MVC but this seems to be a very simple problem.

The error

  • When I go to http://mysite/downloads it works fine
  • When I go to http://mysite/downloads/4.5.6, the controller is correctly called, and the parameter is correctly passed. But then seems that the view is not found. This is the error I found:

enter image description here

like image 859
Daniel Peñalba Avatar asked Sep 16 '14 11:09

Daniel Peñalba


People also ask

How do you pass optional parameters in C#?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

What is index action method in MVC?

You can see in the above action method example that the Index() method is a public method which is inside the HomeController class. And the return type of the action method is ActionResult. It can return using the “View()” method. So, every public method inside the Controller is an action method in MVC.


2 Answers

string? will not work because string is not a value type.

You can set a default value to your parameter:

public ActionResult Index(string version="")
{
    return View(version);
}
like image 105
Anton Maximov Avatar answered Sep 23 '22 11:09

Anton Maximov


The issue is fixed passing the parameter to the view in the following way:

public ActionResult Index(string version)
{
    return View((object)version);
}

Or

public ActionResult Index(string version)
{
    return View("Index", version);
}

When you pass a string model to the view, if the model is a string parameter, it is interpreted as the view name due to the following overload method

View(String viewName)
like image 21
Daniel Peñalba Avatar answered Sep 23 '22 11:09

Daniel Peñalba