简体   繁体   中英

Creating ActionLink in MVC View

I'm fairly new to MVC so, please excuse my possibly incorrect use of terminology.

In the RouteConfig.cs file of my MVC app there is this routes.MapRoute :-

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

The key line being :-

url: "{controller}/{action}/{id}"

so, I followed the example of creating ActionLinks, that were created in my default app template, and cobbled together this line :-

<p>@Html.ActionLink("portfolio details", "Detail", "Portfolio", new { portfolioId = portfolio.PortfolioId } , new { @class = "btn btn-default" })</p>

However, this gives me the URL :-

http://localhost:xxxxx/Portfolio/Detail?portfolioId=174198

If, I don't want the ID to be in a QueryString parameter, how do I create the link to match the pattern that is expected in the routes.MapRoute so that I get a URL link such as :- ?

http://localhost:xxxxx/Portfolio/Detail/174198

你可以用这种方式

<p>@Html.ActionLink("portfolio details", string.Format("Detail/{0}", portfolio.PortfolioId ), "Portfolio", null, null)</p>

Assuming your controller action has the parameter id then you could do:

<p>@Html.ActionLink("portfolio details", "Detail", "Portfolio", new { id = portfolio.PortfolioId } , new { @class = "btn btn-default" })</p>

This should give you:

http://localhost:xxxxx/Portfolio/Detail/174198

The this would pass 174198 to the controller action as the id parameter.

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