I’m trying to query List from database which will be shown in dropdownlistfor in view, and chosen result will be post.
The problem is I’m using two models in view I tried more options
I’m lost with this, I don’t know how to post it. Data are shown in listbox without problem. I’m getting this error when I try to post:
“There is no ViewData item of type ‘IEnumerable’ that
has the key ‘Item2.idcity’.” System.Exception
{System.InvalidOperationException}
CityModel
public class CityModel
{
public int idcity { get; set; }
[Required]
public string cityName { get; set; }
public IEnumerable<CityModel> citys { get; set; }
}
HospitalModel
public class HospitalShowModels
{
[Required]
public string hospitalName { get; set; }
[Required]
public string cityName { get; set; }
}
HospitalControler.Create()
public ActionResult Create()
{
ViewBag.cityModel = new SelectList(DataAccess.DAL.showCity(), "idcity", "cityName");
var tuple = new Tuple<DataAccess.HospitalShowModels, DataAccess.CityModel>(new DataAccess.HospitalShowModels(), new DataAccess.CityModel());
return View(tuple);
}
[HttpPost]
public ActionResult Create(DataAccess.HospitalShowModels model, DataAccess.CityModel model1)
{
if (ModelState.IsValid) {
DataAccess.DAL.insertHospital(model.hospitalName, model1.cityName);
}else{
ModelState.AddModelError("","Invalid options");
}
return View();
}
View.Create
@model Tuple<ProjektZaja.DataAccess.HospitalShowModels,ProjektZaja.DataAccess.CityModel>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Create Hospital</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Item1.hospitalName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Item1.hospitalName)
@Html.ValidationMessageFor(model => model.Item1.hospitalName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Item1.cityName)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => Model.Item2.idcity,(IEnumerable<SelectListItem>)ViewBag.cityModel)
@Html.ValidationMessageFor(model1 => Model.Item2.idcity)
You can’t strongly type a view to multiple models. You need to create a view model which will simply be a composite class containing each of the other two classes, and strongly type the view to that view model.
Then strongly type your view to the view model
And access the models properties appropriately
And bind it in the post method