无法将类型 'System.Collections.Generic.List`1 Models.Hospitals]' 的对象强制转换为类型"System.Collections.Generic.



当在浏览器中单击视图时,我收到了无法转换对象的错误。。。在MVC视图中,这就是医院模式:

public partial class Hospitals
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Hospitals()
{
this.hospital_orders = new HashSet<hospital_orders>();
}

public int hospital_id { get; set; }
public string hospital_name { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<hospital_orders> hospital_orders { get; set; }
}

这是医院订单模型:

public partial class hospital_orders
{
public int order_id { get; set; }
public Nullable<int> hospital_id { get; set; }
public Nullable<int> department_id { get; set; }
public Nullable<int> employee_id { get; set; }
public Nullable<int> status_id { get; set; }
public string order_details { get; set; }
public Nullable<int> user_id { get; set; }
public Nullable<System.DateTime> order_date { get; set; }
public Nullable<System.DateTime> update_date { get; set; }
public Nullable<System.DateTime> deleted_date { get; set; }
public string file { get; set; }

public virtual Departments Departments { get; set; }
public virtual Employees Employees { get; set; }
public virtual Hospitals Hospitals { get; set; }
public virtual order_status order_status { get; set; }
public virtual Users_web Users_web { get; set; }
}

这是控制器创建代码:

public ActionResult Create()
{
var hospName = db.Hospitals.ToList();
List<SelectListItem> listhosp = new List<SelectListItem>();
foreach (var item in hospName)
{
listhosp.Add(new SelectListItem { Text = item.hospital_name, Value = 
item.hospital_id.ToString()});
}
ViewBag.hospitalname = hospName;
return View();
}

这是视图代码:

<div class="form-group">
@Html.LabelFor(model => model.Hospitals.hospital_name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Hospitals.hospital_id,(IEnumerable<SelectListItem>) ViewBag.hospitalname,"Select Hospital", new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.hospital_id, "", new { @class = "text-danger" })

</div>
</div>

该错误出现在dropdownlistfor的行上,如何解决此错误?

我找到了解决方案,Viewbag分配中的错误应该分配给列表不可变如下:

public ActionResult Create()
{
var hospName = db.Hospitals.ToList();
List<SelectListItem> listhosp = new List<SelectListItem>();
foreach (var item in hospName)
{
listhosp.Add(new SelectListItem { Text = item.hospital_name, Value = 
item.hospital_id.ToString()});
}
// ViewBag.hospitalname = hospName;  error here 
ViewBag.hospitalname = listhosp ;
return View();
}

相关内容

最新更新