Search code examples
asp.net-mvchtml-helperdropdown

Asp.net MVC Drop-Down List with Html Helper


I'm Completely confused with lots of articles and tutorials about using html helper to generate drop-down list. my goal is to have 2 drop-down in the first one I need a list of countries, then after choosing a country next drop-down shows tours available for that country. but I'm stuck in the first drop down.

I create a model like this

public class test
{
    public List<Country> Countries { get; set; }   
}

and in my Controller I have this

   {
        var country = db.Countries.ToList();
        var vn = new test { Countries = country.ToList() };
        return View(vn);
    }

and in view foreach loop works correctly and it shows list of countries but my dropdown list has Error and I'm really confused how to fix it.

@model vidiaweb_com.Models.test
<div class="container" id="ttitle">

<nav class="">
    <ul class="resetpadmar">
        @foreach (var t in Model.Countries)
        {
            <li class="">
                <div class="col-md-2 col-sm-2">

                   @t.CountryName

                </div>


            </li>
        }
    </ul>
</nav>

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

appreciate any help


Solution

  • If you do not see loaded data, it is because you does not supply any. You should alter your drop down list as below:

    @Html.DropDownList("Id", 
        Model.Countries.Select(m => new SelectListItem
        {
            Value = m.Id.ToString(),
            Text = m.Name
        }), 
        new { @class = "form-control" })
    

    Or even better, use strongly type version DropDownListFor:

    @Html.DropDownListFor(m => m.Id, 
        Model.Countries.Select(m => new SelectListItem
        {
            Value = m.Id.ToString(),
            Text = m.Name
        }), 
        new { @class = "form-control" })
    

    Note: Text = m.Name should be changed to match your model.