Home Binding async method into DropDownList ASP.NET MVC 5
Reply: 0

Binding async method into DropDownList ASP.NET MVC 5

user3021
1#
user3021 Published in July 18, 2018, 4:58 am

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();
}

HardwareRepository:

public async Task<List<Entities.Hardware>> GetAllHardwareAsync()
        {
            var getAllHardware = await _appContext.Hardwares.ToListAsync();

            return getAllHardware;
        }

View:

<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>

EDIT:

Controller:

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: Controller:

> 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();
}

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>

The problem is that now I want to pass GetAllHardwareAsync to ListOfHardwares and display it via DropDownList. I don't really want to do it by ViewBag. Any ideas? Thanks in advance!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323733 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO