我正在尝试从数据库中查询列表,该列表将显示在 dropdownlistfor 视图中,并且选择的结果将被发布。
问题是我正在使用两个模型,我尝试了更多选项
我迷路了,我不知道如何发布它。数据显示在列表框中没有问题。当我尝试发布时出现此错误:
“没有具有键 'Item2.idcity' 的 'IEnumerable' 类型的 ViewData 项。” System.Exception {System.InvalidOperationException}
城市模型
public class CityModel
{
public int idcity { get; set; }
[Required]
public string cityName { get; set; }
public IEnumerable<CityModel> citys { get; set; }
}
医院模型
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();
}
查看.创建
@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)