duckmike
duckmike

Reputation: 1036

MVC 5 - how to add id into anchor tag

So my view looks like -

@model IEnumerable<PlacingTechiesV3.Models.Category>
<ul>
    @foreach (var item in Model) {
    <li>
        <a href="~/Views/Jobs">@Html.DisplayFor(modelItem => item.CategoryName)</a>
    </li>
    }
</ul>

Within my Category model, I have a field called CategoryId. How do I add that to the href of the anchor tag, so it looks like "~/Views/Jobs/[id]", where [id] is the CategoryId?

Upvotes: 1

Views: 1319

Answers (2)

jimSampica
jimSampica

Reputation: 12410

Use ActionLink instead. It will generate an anchor for you.

@Html.ActionLink(item.CategoryName, "Jobs", "Views", new { id = item.CategoryId })

Upvotes: 1

JanR
JanR

Reputation: 6132

You can just add @item.CategoryId to the href assuming it's part of the item, if it's part of the main model, then it would be @Model.CategoryId

@model IEnumerable<PlacingTechiesV3.Models.Category>
<ul>
    @foreach (var item in Model) {
    <li>
        <a href="~/Views/Jobs/@item.CategoryId">@Html.DisplayFor(modelItem => item.CategoryName)</a>
    </li>
    }
</ul>

Upvotes: 1

Related Questions