MVC Tag Helpers

MVC tag helpers and their Razor equivalent.

To get these new tag helpers to work you need to add the following to your \Views\_ViewImports.cshtml file.

1
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

All of the CSS class references below are from bootstrap.

Anchor

1
2
3
<a asp-action="Delete" asp-route-id="@item.Id">Edit</a>

@Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are you sure you want to delete this entry?');" })

The above is pretty bad as it will allow a GET to a delete action that should rather only accept a POST.
To refactor this to a better design, rather add this to your view:

1
2
3
4
5
<form asp-action="Delete" asp-route-id="@item.Id">
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Index" asp-route-id="@item.Id" asp-controller="EntryPlatform">Platform</a> |
<input type="submit" value="Delete" class="btn-link" onclick="return confirm('Are you sure you want to delete this entry?');" />
</form>

Then in your controller add:

1
2
3
4
5
6
7
8
9
// POST: LexiconEntry/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
_repository.Delete(id);
TempData["message"] = "Entry deleted successfully.";
return RedirectToAction("Index");
}

Input

Works with anything like string, datetime, double

1
2
3
4
5
<input asp-for="Name" class="form-control" />
<input asp-for="Salary" class="form-control" />
<input asp-for="SomeDate" class="form-control" />

@Html.TextBox("Description", null, new { @class = "form-control" })

You can also store this as a cookie or session.

1
<input type="hidden" asp-for="Id" />

Span Validation For

1
<span asp-validation-for="Description" class="text-danger"></span>

Lable for

1
<label asp-for="Recommendation" class="control-label"></label>

Display

1
2
3
4
5
6
@Html.DisplayNameFor(model => model.Name)

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
1
@Html.DropDownListFor(Model => Model.SubCategoryId, (List<SelectListItem>)ViewData["SubCategory_SelectList"], "-- Please Select --", new { @class = "form-control" })

Partial

1
2
3
4
5
6
7
8
9
<div id="divResults">
<partial name="~/Views/Entry/_Table.cshtml" model="Model" />
</div>

<div id="divResults">
@{
@Html.Partial("~/Views/Entry/_Table.cshtml", Model);
}
</div>

References