简体   繁体   中英

Getting an Actionresult Parameter in MVC4

I'm working on a simple MVC application, where I am generating below path

@Html.ActionLink(@objcity.CityName, "AgentProfiles", "Home", new {@Id=objcity.MaProvision.ProvinceName+"/"+@objcity.CityName }, null)

It makes a url like this:

http://localhost:45896/Home/AgentProfiles/Ontario/testt

In the controller I have written this method:

public ActionResult AgentProfiles(String Id)
{
    //Code
}

Is it possible to get in /Ontario/testt in Id variable?

You want to get /Ontario/testt in Id(route parameter) for this you have to modify your default routes little bit or you have to make a custom route but in my opinion for your simple requirement try below answer.

Instead of

@Html.ActionLink(@objcity.CityName, "AgentProfiles", "Home", new {@Id=objcity.MaProvision.ProvinceName+"/"+@objcity.CityName }, null)

Modify Actionlink this way

@Html.ActionLink(@objcity.CityName, "AgentProfiles", "Home", new { ProvinceName=objcity.MaProvision.ProvinceName ,CityName = objcity.CityName }, null)

Controller Action :

public ActionResult AgentProfiles(string ProvinceName,string CityName ) //get ProvinceName and CityName which will be coming as querystring variables as shown here.
{......}

OR

EDIT :- Try this as per your comment.

Add one more route in RouteConfig.cs file inside AppStart folder as shown below :

routes.MapRoute(
      "MvcRoutes",                                            // Route name
      "{controller}/{action}/{provincename}/{cityname}",     // URL with parameters
      new { controller = "Home", action = "Index", provincename = "", cityname= "" }  // Parameter defaults
);

Don't forget to put this custom route above default route.

Modify ActionLink as shown below :

 @Html.ActionLink(@objcity.CityName, "AgentProfiles", "Home", new { provincename = objcity.MaProvision.ProvinceName , cityname = objcity.CityName }, null)

Controller Action :

public ActionResult AgentProfiles(string provincename ,string cityname) 
{......}

you can modify your routing like-

  {controller}/{action}/{*catchall}

and in action method

public ActionResult AgentProfiles(string catchall)
{
// your code
}

Then you will have value /Ontario/testt in your catchall parameter which you can use in action method.

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