简体   繁体   中英

Change route url in asp.net mvc

I have Login Controller and Register ActionResult

   public ActionResult Register()
        {
            return View();
        }

If i post any data to Register actionresult url seems like below,

WebSiteName/Login/Register

I want to change route url as WebSiteName/Login/Reg=Id?

So i tried below however i could not change route url.

   routes.MapRoute(
         name: "something",
         url: "Login/Reg=Id?",
         defaults: new
         {
             controller = "Login",
             action = "Register",
             id = id = UrlParameter.Optional
         }
     );

So how can i change url in asp.net mvc ?

Any help will be appreciated.

Thanks.

You are trying to use incorrect form of a url parameter. The options you have are:

  1. Url part parameter: WebSiteName/Login/Reg/{id}

    For this you can use following config

     routes.MapRoute( name: "something", url: "Login/Reg/{id}", defaults: new { controller = "Login", action = "Register", id = UrlParameter.Optional } ); 
  2. Query string parameter: WebSiteName/Login/Reg?id={id}

    Here you do not need to specify the parameter in config at all:

     routes.MapRoute( name: "something", url: "Login/Reg", defaults: new { controller = "Login", action = "Register" } ); 

Of course in both cases it is assumed your action Register has parameter id.

Here I've remove last two passing parameter from the URL

this is my url link -> http://localhost:12345/User?value=98998?id=2

and I want to remove value and id parameter from the url link

Step-I

Modify your Routeconfig.cs like this

routes.MapRoute(
   "User",
   "User/{value}/{id}",
   new { controller = "User", action = "Index", value= UrlParameter.Optional, id = UrlParameter.Optional }
);

Step-II

User Controller

public ActionResult Index(string value, int id)
{
    // write Your logic here 
    return view();
}

Step-III

Create an Index view for UserController

@Html.ActionLink("LinkName", "Index", "User", new {value = "98998", id = "2"},null)

Finally we got a result: http://localhost:12345/User/98998/2

Likewise we can remove multiple parameter from the url

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