Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Razor page dropdown list

Tags:

c#

asp.net

razor

 <div class="form-group">
            @Html.LabelFor(model => model.CountyId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CountyId, "", new { @class = "text-danger" })
            </div>
        </div>

So I have the following code on my website. What I want to do is instead of having a text field where you type the countyID I would like to have the county name dropdown list where the user selects it by name and it would still register as a number. (For example instead of writing "1" he would just click and choose County1 from a list I make)

Edit: Alright now I have this code

@Html.DropDownList("Counties", new List<SelectListItem>
                   {
                       new SelectListItem {Text = "Alba", Value = "1", Selected = true },
                       new SelectListItem {Text = "Arad", Value = "2" },
                       new SelectListItem {Text = "Arges", Value = "3" },
                       new SelectListItem {Text = "Bacau", Value = "4" },
                   }, "Select County")
                @Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { @class = "form-control" } })

How do I write it to replace the @Html.EditorFor(model => model.CountyId with the DropDownList selection?

Edit2: how do I use @Html.DropDownListFor ?

like image 502
Buda Cristian Avatar asked Dec 27 '15 16:12

Buda Cristian


1 Answers

Buda, please try below

 <div class="form-group">
            @Html.LabelFor(model => model.CountyId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               @Html.DropDownListFor(model => model.CountyId, new List<SelectListItem>
                       {
                           new SelectListItem {Text = "Alba", Value = "1", Selected = true },
                           new SelectListItem {Text = "Arad", Value = "2" },
                           new SelectListItem {Text = "Arges", Value = "3" },
                           new SelectListItem {Text = "Bacau", Value = "4" },
                       }, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CountyId, "", new { @class = "text-danger" })
            </div>
        </div>
like image 124
Felix Cen Avatar answered Sep 28 '22 03:09

Felix Cen