【问题标题】:How to generate a link that has the Name property instead of the Id如何生成具有 Name 属性而不是 Id 的链接
【发布时间】:2016-11-22 18:04:52
【问题描述】:

我使用这个生成链接:

@Html.ActionLink(page, "Nouvelle", "Pages", new { Id = @item.Jeton }, null)

我的控制器:

public ActionResult Nouvelle(int Id)
        {
            var sliders = db.Actualite.Where(a => a.Afficher).OrderByDescending(a => a.Date_publication);
            var partenaires = db.Partenaire.Where(p => p.Afficher);
            var nouvelle = db.Actualite.Where(a => a.Jeton == Id).First();
            var model = new ModelNouvelle { Slider = sliders, Partenaire = partenaires, Nouvelle = nouvelle };

            return View(model);
        }

生成的链接是这样的:

http://something.org/Pages/Nouvelle/1

我想获得一个包含名称而不是 ID 的链接:

http://something.org/Pages/Nouvelle/More-like-this

【问题讨论】:

    标签: c# asp.net-mvc razor hyperlink


    【解决方案1】:

    我不明白为什么不......你只是改变你的路线属性..并改变你的方法签名为你的行动..

    像这样:

    控制器:

    public ActionResult Nouvelle(string routeValue)
        {
            var sliders = db.Actualite.Where(a => a.Afficher).OrderByDescending(a => a.Date_publication);
            var partenaires = db.Partenaire.Where(p => p.Afficher);
            var nouvelle = db.Actualite.Where(a => a.Jeton /*this needs to be changed to the property that is doing the comparison*/ == routeValue).First();
            var model = new ModelNouvelle { Slider = sliders, Partenaire = partenaires, Nouvelle = nouvelle };
    
            return View(model);
        }
    

    ActionLink:

    @Html.ActionLink(page, "Nouvelle", "Pages", new { routeValue = @item.PropertyName /*whatever property holds the value that you want in your link*/ }, null)
    

    如果这有帮助,请告诉我。

    【讨论】:

    • 是的,正是我需要的!
    • @SteveMorin 很高兴我能帮上忙!请将答案标记为已接受,以便此问题显示已回答
    • 在 1 分钟内完成,因为似乎有一个计时器。即使 Saket 的回答速度更快,我也会使用您的答案,因为您的解决方案提供了更多详细信息。
    【解决方案2】:

    使用字符串作为参数修改您的操作。

    public ActionResult Nouvelle(string _name)
    

    在您的操作链接中

    @Html.ActionLink(page, "Nouvelle", "Pages", new { _name = "More-like-this" }, null)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多