Hi @Atif Shah ,
When set the asp-items
attribute, we need to use @( {the c# code} )
.
You can refer the following code to populate the select tag using the service.
View page:
@model MVCWebApplication.Models.MyViewModel
@using MVCWebApplication.Services
@inject IServiceRepository _servicerepo
<div class="row">
<div class="col-md-4">
<form asp-action="SelectIndex">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label>Lucky Employee</label>
<select asp-for="EmployeeId" asp-items="@(await _servicerepo.populateSelectList("proc1", "valuea"))" >
<option>Please select one</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
ServiceRepository.cs file:
public interface IServiceRepository
{
Task<List<SelectListItem>> populateSelectList(string procedure, string firstval);
}
public class ServiceRepository : IServiceRepository
{
public Task<List<SelectListItem>> populateSelectList(string procedure, string firstval)
{
return Task.Factory.StartNew(() =>
{
return new List<SelectListItem>()
{
new SelectListItem() { Value = "aa", Text = "AA_" + procedure },
new SelectListItem() { Value = "bb", Text = "BB_" + procedure },
new SelectListItem() { Value = "cc", Text = "CC_" + procedure }
};
});
}
}
And the model:
public class MyViewModel
{
public string EmployeeId { get; set; }
public string Comments { get; set; }
}
The output like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Dillion