I Created a form on my Asp.core project.Now I want to add a drop down list for show states and city on that form.
I create a model and view model:
[Required(ErrorMessage = "Required")]
public string Title { get; set; }
public long? ParentId { get; set; }
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
and write some method to access it on my repository and service:
Repository:
public async Task<List<UserLocationViewModel>> GetStateForUserInfo()
{
return await _context.Locations.Where(l => l.ParentId == null)
.Select(l => new UserLocationViewModel()
{
Title = l.Title,
}).ToListAsync();
}
public async Task<List<UserLocationViewModel>> GetCityForUserInfo(long locationId)
{
return await _context.Locations.Where(l => l.ParentId == locationId)
.Select(l => new UserLocationViewModel()
{
Title = l.Title,
}).ToListAsync();
}
and service:
public async Task<List<UserLocationViewModel>> GetStateForUserInfo()
{
return await _packageRepository.GetStateForUserInfo();
}
public async Task<List<UserLocationViewModel>> GetCityForUserInfo(long locationId)
{
return await _packageRepository.GetCityForUserInfo(locationId);
}
then on controller I call these method and return to view with view data:
ViewData["State"] = _packageService.GetStateForUserInfo();
ViewData["City"] = _packageService.GetCityForUserInfo(packageId);
in view I call it :
@{
ViewData["Title"] = _localizer["GetUserInfo"];
IEnumerable<UserLocationViewModel> State = ViewData["State"] as IEnumerable<UserLocationViewModel>;
IEnumerable<UserLocationViewModel> city = ViewData["City"] as IEnumerable<UserLocationViewModel>;
}
But when I want to access it on select tag I cant access to my properties:
<select asp-for= "?????" class="form-control ">
</select>
UPDATE: First read my repository to get location Id: but I have error
then in controller I need the id so I write:
var firstLocationId = state.FirstOrDefault()?.Id;
var city = await _packageService.GetCityForUserInfo(firstLocationId);
ViewData["City"] = new SelectList(city, "Title", "Title");

Here is a sample you could follow:
Model:
View:
For
public SelectList(IEnumerable items, string dataValueField, string dataTextField);, the first parameter is the source, the second parameter is each option value in select, the third parameter is that each option displays text in html.Controller:
If you want to post the selected city or state to controller:
Index.cshtml:
The mapped property in
asp-forshould be the same type withdataValueField(Titlehere).Controller:
Result:
Update:
Two ways display dropdownlist:
First one:
Razor view:
Second one:
Razor view: