Path null parameter

Asked

Viewed 525 times

1

I’m trying to get into a controller, receive a parameter and print it in the View by a ViewData or ViewBag.

My Controller:

public ActionResult Index(string information)
    {
        ViewData["Bag"] = information;
        return View();
    }

My View:

@ViewData["Bag"]

The problem is that the parameter information is null every time I pass the URL call for example: http://localhost/Home/Index/teste.

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

This is the standard route.

  • you need this parameter? if yes you can put string? to allow this to come null to the controller

  • i need you to take yes, but when I put the url http://localhost/Home/Index/test Asp.net-mvc it should take the string information = "test"

  • 2

    How is your file RouteConfig? I’m asking because you posted Action index from your controller, and is accessing Home/Index/Teste. If your route is wrong, you need to access it like this: Home/Index?information=Teste

  • I believe it’s the way Randrade wrote, which is the default route behavior, so you’d get the value Teste for the variable information correctly in your Actionresult.

  • the path is default Routes.Maproute( name:"Default1", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = Urlparameter.Optional });

  • Andre, creates a Model, adds the Model reference in the view and the controller, fills in the Model. It should work.

Show 1 more comment

2 answers

3


The problem is that your default route expects an "id" parameter and not an "information" parameter".

In the action, change the parameter name to "id" or change its path so that it receives an "information" and not an "id".

3

Add a new route, so you don’t need to modify the URI.

routes.MapRoute( name:"Information", url: "{controller}/{action}/{information}", defaults: new { controller = "Home", action = "Index", information = string.Empty });

Adding this route should solve the problem. However it is valid to remember that another route with a parameter string may have routing problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.