Steve Morin
Steve Morin

Reputation: 156

How to generate a link that has the Name property instead of the Id

I generate links using this :

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

My controller :

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);
        }

The link resulting is something like this :

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

I would like to get a link that has the name instead of the Id like :

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

Upvotes: 3

Views: 49

Answers (2)

Grizzly
Grizzly

Reputation: 5943

I don't see why not.. you just change your route attributes.. and also change your method signature for your action..

so like this:

Controller:

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)

let me know if this helps.

Upvotes: 1

Saket Choubey
Saket Choubey

Reputation: 916

Modify your action with string as parameter.

public ActionResult Nouvelle(string _name)

In your action link

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

Upvotes: 1

Related Questions