user455100
user455100

Reputation: 151

ASP.NET MVC: How can I pass a querystring variable

I've worked on web forms for a while and am not used to mvc.

Here is what i want to do:

<% if guest then %>
    URL.RouteURL("AcccountCreate?login=guest")
<% end if %>

However I can't do this because it says a route with this name has not been created. And I am assuming it would be silly to create a route for this.

Upvotes: 2

Views: 7106

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039358

<%= Url.Action("AcccountCreate", new { login = "guest" }) %>

or if you want to generate directly a link:

<%= Html.ActionLink("create new account", "AcccountCreate", new { login = "guest" }) %>

You can also specify the controller:

<%= Html.ActionLink(
    "create new account", // text of the link
    "Acccount", // controller name
    "Create", // action name
    new { login = "guest" } // route values (if not part of the route will be sent as query string)
) %>

Upvotes: 3

Dustin Laine
Dustin Laine

Reputation: 38543

That is not really now MVC routing was intended to be used. Better to set your URL like:

AccountCreate/guest

And then have your action accept that parameter

public ActionResult AccountCreate(string AccountName)
{
    //AccountName == guest
    return View();
}

Then you could have a routing entry like:

routes.MapRoute(
    "AccountCreate", // Route name
    "{controller}/{action}/{AccountName}", // URL with parameters
    new { controller = "AccountCreate", action = "Index", AccountName = UrlParameter.Optional } // Parameter defaults
);

However, with that if you create an actionlink with a parameter and no matching route it will create a querystring variable for you.

Upvotes: 1

Related Questions