MVC3使用dropdownlistfor从数据库提交两个模型视图

时间:2013-01-05 11:23:50

标签: c# asp.net-mvc-3 ienumerable html.dropdownlistfor

我正在尝试从数据库中查询List,它将显示在dropdownlistfor中,所选结果将被发布。

问题是我在视图中使用了两个模型我尝试了更多选项

我迷失了,我不知道如何发布。数据显示在列表框中没有问题。当我尝试发布时,我收到此错误:

  

“没有'IEnumerable'类型的ViewData项   键有'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)

2 个答案:

答案 0 :(得分:0)

视图中的模型类型应与后期操作中的模型类型匹配。因此它应该是一个元组(虽然我个人不会使用它)或具有2个属性的新模型类型(一个用于城市,一个用于医院)

答案 1 :(得分:0)

您无法为多个模型强烈键入视图。您需要创建一个视图模型,它只是一个包含其他两个类的复合类,并强烈键入该视图模型的视图。

public class CreateViewModel
{
  public CityModel CityModel {get; set;}
  public HospitalShowModel HospitalShowModel {get; set;}
}

然后强烈地将视图输入到视图模型

@ model Full.Path.To.CreateViewModel

并正确访问模型属性

Model.CityModel.cityName //etcetera...

并在post方法中绑定它

[HttpPost]
public ActionResult Create(CreateViewModel viewModel)
{
  //...