Computer Magic Logo
select

Wednesday, March 22, 2017

Published by Aristotelis Pitaridis

Let’s see how to use the select tag helper in a form. We have the following model which will be used by our example.

public class Student
{
    public string CountryCode { get; set; }
}

In our action we use the ViewBag to define the list which will be used by the select element.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewBag.Countries = new List<SelectListItem>
        {
            new SelectListItem { Text = "Greece", Value = "GR" },
            new SelectListItem { Text = "United Kingdom", Value = "UK" },
            new SelectListItem { Text = "Italy", Value = "IT" }
        };
        return View();
    }
}

Now at the top of the view we define the model which will be used by our view.

@model Student

Finally, we have the form tag helper which contains our select tag helper.

<form asp-controller="Home" asp-action="Index">
    <select asp-for="CountryCode" asp-items="ViewBag.Countries"></select>
    <input class="btn btn-success" type="submit" />
</form>

This code will generate the following HTML.

<form action="/" method="post">
    <select id="CountryCode" name="CountryCode">
        <option value="GR">Greece</option>
        <option value="UK">United Kingdom</option>
        <option value="IT">Italy</option>
    </select>
    <input class="btn btn-success" type="submit" />
    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8Cc6bJ3TWmVAoCQJZSt8GLuyGCnNfcP4s-EOrjVuR8oWKfGHXHbEDVQpuUf_noa5RQsWFwpizTljAmxOHH8tKKix2MyTnBxN_fesaTQus5KqUbnNa0OvLsKmUY-B-qElNTskiDVB1oDWRiW4i_wC2F8" />
</form>