简体   繁体   中英

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.

<%= 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)
) %>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM