Ydhem
Ydhem

Reputation: 928

Parameters after url Asp net mvc

I would like to have some paramaters after my website's URl. So, mysite.com/ThisIsMyStringMessage, would show this :

Hello, ThisIsMyStringMessage.

Of course, the view related to the action contains this :

Hello, @ViewBag.Message

And the HomeController :

   public ActionResult Index(string message)
    {
        ViewBag.Message = message;
        return View();
    }

Edit related to comments :

@Zim, I'll have more than one controller.

@Jessee, So that's what I'm doing here, thank you, I didn't know really what I was doing.

Upvotes: 1

Views: 248

Answers (2)

Ant P
Ant P

Reputation: 25221

With the default routing, ThisIsMyStringMessage will be picked up as the Controller, not as an Action method parameter. You will need a custom route to be able to do this. Try the following before the default route in Global.asax:

routes.MapRoute(
    "RootWithParameter",
    "{message}", 
    new { controller = "Home", action = "Index", message = UrlParameter.Optional }
);

Alternatively, access the method with mysite.com?message=ThisIsMyStringMessage

Upvotes: 2

Steven V
Steven V

Reputation: 16585

You will need to take a look at your RouteConfig.cs or Global.asax to setup a route with the parameter of message instead of id. Right now it probably looks like:

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

You would need to change the url parameter to something like {controller}/{action}/{message} for that to work.

Also, be careful with passing strings in the URL. ASP.NET (and some modern browsers) gives you many security protections to prevent people from doing nasty stuff like XSS, but it's probably not a habit you want to create.

Upvotes: 1

Related Questions