您好我使用viewmodel并且在我的控制器中无法将列表转换为实体。
这是我的viewmodel:
namespace SmartAdvertising.Backend.Models
{
public class DashboardModel
{
public Advert allAdvert { get; set; }
public Advert allAdvert2 { get; set; }
}
}
控制器:
public ActionResult Dashboard()
{
string email_uzivatele = (String)Session["email"];
DashboardModel adverts = new DashboardModel();
List<Advert> time = AdvertServiceLayer.Instance.SelectAllWith(email_uzivatele, "Reklama na určitou dobu");
List<Advert> price = AdvertServiceLayer.Instance.SelectAllWith(email_uzivatele, "Reklama na určitou částku");
adverts.allAdvert = time;
adverts.allAdvert2 = price;
return View(adverts);
}
查看:
@model IList<SmartAdvertising.Backend.Models.DashboardModel>
@{
ViewBag.Title = "Dashboard";
}
<h1>@ViewBag.Title</h1>
<div class="row">
<div class="col-md-12 col-sm-12">
<h2>Všechny reklamy na určitou dobu</h2>
<table class="table-hover" style="width:100%">
<tr>
<th>
Název reklamy
</th>
<th>
Typ reklamy
</th>
<th>
Cena reklamy
</th>
<th>
Email uživatele
</th>
<th>
Datum začátku
</th>
<th>
Datum konce
</th>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.nazev_reklamy
</td>
<td>
@item.typ_reklamy
</td>
<td>
@item.cena_reklamy
</td>
<td>
@item.email_uzivatele
</td>
<td>
@item.datumz
</td>
<td>
@item.datumk
</td>
</tr>
}
</table>
</div>
<div class="col-md-12 col-sm-12">
<h2>Všechny reklamy na určitou částku</h2>
<table class="table-hover" style="width:100%">
<tr>
<th>
Název reklamy
</th>
<th>
Typ reklamy
</th>
<th>
Cena reklamy
</th>
<th>
Email uživatele
</th>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@item.nazev_reklamy
</td>
<td>
@item.typ_reklamy
</td>
<td>
@item.cena_reklamy
</td>
<td>
@item.email_uzivatele
</td>
</tr>
}
</table>
</div>
<div class="col-md-12 col-sm-12">
</div>
</div>
但是在视图中它给出了这个错误:
Error 1 foreach statement cannot operate on variables of type 'SmartAdvertising.Backend.Models.DashboardModel'
because 'SmartAdvertising.Backend.Models.DashboardModel' does not contain a public definition for 'GetEnumerator'
在控制器这两行:
adverts.allAdvert = time;
adverts.allAdvert2 = price;
给了我这个错误:
Error 3 Cannot implicitly convert type 'System.Collections.Generic.List<SmartAdvertising.Entities.Advert>'
to 'SmartAdvertising.Entities.Advert'
答案 0 :(得分:1)
模型中的属性必须是List:
类型public class DashboardModel
{
public List<Advert> allAdvert { get; set; }
public List<Advert> allAdvert2 { get; set; }
}
此外,您必须遍历模型的属性:
@foreach (var item in Model.allAdvert)