如何解决无法将类型为“ System.Collections.Generic.List`1 Models.Hospitals”的对象转换为类型为“ System.Collections.Generic.IEnumerable”的对象
在浏览器中单击视图时,出现此错误,无法在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; }
}
这是hospital_orders模型:
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分配中的错误分配给list 不要像下面这样变:
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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。