如何生成具有Name属性而不是Id的链接

时间:2016-07-19 17:55:24

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

我用这个生成链接:

@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

2 个答案:

答案 0 :(得分:1)

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

public ActionResult Nouvelle(string _name)

在您的操作链接中

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

答案 1 :(得分: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)

请告诉我这是否有帮助。