Hej,
to co chce osiągnąć: mam dwa dropDownFor, na podstawie wartości z pierwszego wczytuje wartości do drugiego, w jednym projekcie mi to działa obecnie nie umiem tego zrobić na nowo :/
Taki dostaje błąd:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'AirportIdField'.
Tutaj jest kod głównego widoku:
@{
var ajaxOptions = new AjaxOptions
{
UpdateTargetId = "o",
OnSuccess = @"onAjaxSuccess()"
};
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
var onAjaxSuccess = function () {
$('#AirportId').val($('#AirportIdField').val());
$('#AirportIdField').change(function () {
$('#AirportId').val($('#AirportIdField').val());
});
};
$(function () {
$('#CountryId').val($('#CountryIdField').val());
$('#form-id').submit();
$('#AirportId').val($('#AirportIdField').val());
$('#AirportIdField').change(function () {
$('#form-id').submit();
$('#AirportId').val($('#AirportIdField').val());
});
});
</script>
<br />
@using (Ajax.BeginForm("Airports", null, ajaxOptions, new { id = "form-id" }))
{
<div class="form-group">
@Html.Label("Choose Country", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CountryIdField", (SelectList)ViewBag.country, "---Select---")
</div>
</div>
}
<br />
<div id="o">
@Html.Partial("Airports")
</div>
<br />
<br />
@using (Html.BeginForm("Add", "Flight"))
{
@Html.Hidden("CompanyId")
@Html.Hidden("AirportId")
@Html.Hidden("CarId")
<input type="submit" name="Add" />
}
tutaj jest kod ładujący dane do drugiego dropdownFor:
<div class="form-group">
@Html.Label("Choose airport", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AirportIdField", (SelectList)ViewBag.airports)
</div>
</div>
kontroller:
public ActionResult Index()
{
ViewBag.country = new SelectList(this.countryRepository.Countries(), "Id", "Name");
ViewBag.airport = new SelectList(this.airportRepository.Airports().OfType<Airport>(), "Id", "Name");
return this.View();
}
public PartialViewResult Airports(int countryIdField = 0)
{
List<Airport> items = this.airportRepository.Airports().Where(x => x.Country.Id == countryIdField).ToList();
var listItems = items.Select(x => new { Id = x.Id, Name = String.Format("{0}", x.Name) });
ViewBag.airports = new SelectList(listItems, "Id", "Name");
return this.PartialView();
}
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
[HttpPost]
public ActionResult Add(FlightModel data)
{
return RedirectToAction("Index");
}