Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - MVC6 Dropdownlist of Countries

I am trying to use MVC6 Tag Helpers to create a dropdownlist of CountryCode and CountryName so that a user can select their country after registering. The relevant part of the view looks like this so far

<form asp-controller="Manage" asp-action="EditCountry" asp-route-returnurl="@ViewData["ReturnUrl"]">
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<select asp-for="CountryCode" asp-items="@Model.Countries"></select>

The relevant part of the viewmodel looks like this

[Display(Name = "Country")]
public string CountryCode { get; set; }
public IEnumerable<Country> Countries { get; set; }

A Country looks like this

public partial class Country
{
    [Key]
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; set; }
}

The controller returns a list of countries to the viewmodel

var model = new IndexViewModel
{
    CountryCode = user.CountryCode,
    Countries =_customersContext.Countries.OrderBy(c=>c.CountryName),
};
return View(model);

but in the view asp-items="@Model.Countries" has a squiggly Cannot convert Country to SelectListItem

Also I cannot find how in the form to specify CountryCode as the property to return and CountryName as the property to display.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way I make my dropdowns is somewhat similar except that in my ViewModel, my property is of type SelectList instead of an IEnumerable<>.

public class HomeViewModel
{
    public string CountryCode { get; set; }
    public SelectList CountryList { get; set; }
}

Then in the controller I get the data and convert it to an anonymous list with two properties “Id” and “Value”.

In turn, I create a new SelectList() passing in the anonymous list specifying what is the dataValueField and what is the dataTextField.

public IActionResult Index()
{
    var countries = _customersContext.Countries.OrderBy(c => c.CountryName).Select(x => new { Id = x.Code, Value = x.Name });

    var model = new HomeViewModel();
    model.CountryList = new SelectList(countries, "Id", "Value");

    return View(model);
}

Finally, in the View:

<div class="form-group">
    <label asp-for="CountryCode" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <select asp-for="CountryCode" asp-items="@Model.CountryList"></select>
    </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...