【发布时间】:2018-05-20 08:51:26
【问题描述】:
MachineDto:
[Required(ErrorMessage = "This field is required")]
[Display(Name = "Hardware Type")]
public string HardwareType { get; set; }
public IEnumerable<SelectListItem> ListOfHardwares { get; set; }
IHardwareRepository:
public interface IHardwareRepository
{
Task<Entities.Hardware>> GetAllHardwareAsync();
}
硬件存储库:
public async Task<List<Entities.Hardware>> GetAllHardwareAsync()
{
var getAllHardware = await _appContext.Hardwares.ToListAsync();
return getAllHardware;
}
查看:
<div class="form-group">
@Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.HardwareType, Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })
</div>
</div>
编辑:
控制器:
public class HardwareController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public HardwareController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<ActionResult> DisplayAll()
{
var displayAll = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
return View(displayAll);
}
}
EDIT2: 控制器:
> public async Task<ActionResult> Add()
> {
> var model = new ImageDto();
> var hardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
>
> model.ListOfHardwares = hardwares.Select(h => new SelectListItem
> {
> Text = h.Name,
> Value = h.Description
> });
>
> return View();
}
查看:
@model MachineDto
<div class="form-group">
@Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })
</div>
问题是现在我想将 GetAllHardwareAsync 传递给 ListOfHardwares 并通过 DropDownList 显示它。我真的不想通过 ViewBag 来做。有任何想法吗? 提前致谢!
【问题讨论】:
标签: asp.net entity-framework asynchronous asp.net-mvc-5 async-await