Вот некоторые примеры код, который вы можете изменить и использовать в своем сценарии. Я не знаю, как выглядит ваш код, поэтому я создал свой собственный.
На ваш взгляд:
@model YourProject.ViewModels.YourViewModel
Ваше расположение выпадающий:
<td><b>Location:</b></td>
<td>
@Html.DropDownListFor(
x => x.LocationId,
new SelectList(Model.Locations, "Id", "Name", Model.LocationId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.LocationId)
</td>
Ваше мнение Модель:
public class YourViewModel
{
// Partial class
public int LocationId { get; set; }
public IEnumerable<Location> Locations { get; set; }
}
Ваш создать метод действия:
public ActionResult Create()
{
YourViewModel viewModel = new YourViewModel
{
// Get all the locations from the database
Locations = locationService.FindAll().Where(x => x.IsActive)
}
// Return the view model to the view
// Always use a view model for your data
return View(viewModel);
}
[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Locations = locationService.FindAll().Where(x => x.IsActive);
return View(viewModel);
}
// If you browse the values of viewModel you will see that LocationId will have the
// value (unique identifier of location) already set. Now that you have this value
// you can do with it whatever you like.
}
Ваш класс местоположение:
public class Location
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
Это просто, как может прийти.Я надеюсь, что это помогает :)
UPDATE:
Мой уровень службы есть для любого дальнейшего бизнес-логики, а затем он называет мое хранилище слой, чтобы получить данные из базы данных. Сначала я использую код Entity Framework. Я также использую Autofac для моего контейнера IoC.
Ваш уровень услуг:
public class LocationService : ILocationService
{
private readonly ILocationRepository locationRepository;
public LocationService(ILocationRepository locationRepository)
{
this.locationRepository = locationRepository;
}
public IEnumerable<Location> FindAll()
{
return locationRepository.FindAll();
}
}
И ваше хранилище:
public class LocationRepository : ILocationRepository
{
YourDbContext db = new YourDbContext();
public IEnumerable<Location> FindAll()
{
return db.Locations.OrderBy(x => x.Name);
}
}
Ваш контекст базы данных класс:
public class YourDbContext : DbContext
{
public DbSet<Location> Locations { get; set; }
}
попробовать решение Brendan Vogt, он будет работать – learning