ASP.NET如何基于控制器模板和动作模板生成带属性路由的URL

问题描述 投票:0回答:1

我在 IdeasController 中有以下 url 模板:

[Controller]
[Route("/gemeente/{municipalityName}/election/{electionId}/ideas/"Name = "Ideas")]

public class IdeasController : Controller

我也有这个带有路线模板的动作:

 [Route("theme/{themeId}/",Name = "GetTheme")]
    public IActionResult GetTheme(int themeId)
    {
        Console.WriteLine("Get theme----------------------------");
        
        IEnumerable<Idea> ideas = _ideasManager.GetIdeasByTheme(themeId);
        GeneralTheme theme = _themeManager.GetGeneralTheme(themeId);
        IdeasByThemeDto ideasByThemeDto = new IdeasByThemeDto
        {
            Ideas = ideas,
            Theme = theme
        };
        ViewBag["Title"] = "Ideas by theme: " + theme.Name;
        
        return View("IdeasByTheme", ideasByThemeDto);
    }

如何生成 URL 以在视图中到达

gemeente/Dendermonde/election/1/ideas/theme/2

具体例子见:

我有一个想法集合,每个想法都有一个带有 themeId 的主题, 我想生成一个附加当前 url (

/gemeente/{municipalityName}/election/{electionId}/ideas/
) 和主题 id (
theme/{themeId}
) 的 Url。所以基本上将两个(“Ideas”和“GetTheme”)模板组合在一起。

在视图中:

@Url.RouteUrl("GetTheme22", new { themeId = Model.Theme.Id })  //empty string

注意:根据之前的请求,市政当局名称和选举 ID 也应动态插入

c# asp.net attributerouting
1个回答
1
投票

鉴于显示的路线模板,您可以使用

Url.RouteUrl
生成链接:

<a href="@Url.RouteUrl("GetTheme", new {municipalityName="Dendermonde", electionId=1, themeId=2})">Get Themes</a>

这将解决

<a href="gemeente/Dendermonde/election/1/ideas/theme/2">Get Themes</a>

参考路由到 ASP.NET Core 中的控制器操作 - 通过路由生成 URL

MunicipalitName
electionId
如何动态插入

如何将信息传递给视图取决于您的偏好。

在这里,以下内容从

ViewBag
中提取控制器模板参数,假设它是从上一个请求中存储在那里的

<a href="@Url.RouteUrl("GetTheme", new {
    municipalityName=ViewBag["MunicipalitName"], 
    electionId=ViewBag["electionId"], 
    themeId=Model.Theme.Id})">Get Themes</a>

虽然以下假设所有内容都存储在模型中

<a href="@Url.RouteUrl("GetTheme", new {
    municipalityName=Model.Idea.MunicipalitName, 
    electionId=Model.Idea.ElectionId, 
    themeId=Model.Theme.Id})">Get Themes</a>
© www.soinside.com 2019 - 2024. All rights reserved.