[英]When display data from table in ASP.NET Core 5 MVC on view model nothing display although table have multiple rows?
我正在開發 ASP.NET Core 5 MVC 應用程序。 我有一個 5 行的桌子cinimas
。
我的問題是我無法在自定義視圖 model 中顯示這 5 行。
我試過了,但沒有顯示任何行。
我嘗試了什么:
第一步:model創建
public class Cinema : IEntityBase
{
[Key]
public int Id { get; set; }
[Display(Name = "Cinema Logo")]
[Required(ErrorMessage = "Cinema logo is required")]
public string Logo { get; set; }
[Display(Name = "Cinema Name")]
[Required(ErrorMessage = "Cinema name is required")]
public string Name { get; set; }
}
第 2 步:創建自定義 model 視圖,它將數據顯示為表中的視圖模型:
public class CinimaViewModels
{
public string Logo { get; set; }
public string Name { get; set; }
}
第 3 步:創建服務接口ICinemasService
並定義數據顯示:
public interface ICinemasService:IEntityBaseRepository<Cinema>
{
IQueryable<CinimaViewModels>GetAllCinimas();
}
第 4 步:在CinemasService
class 中實現該接口
public class CinemasService:EntityBaseRepository<Cinema>, ICinemasService
{
private readonly AppDbContext _context;
public CinemasService(AppDbContext context) : base(context)
{
_context = context;
}
public IQueryable<CinimaViewModels> GetAllCinimas()
{
var cinmas = new Cinema();
var response = new List<CinimaViewModels>
{
new CinimaViewModels
{
Description = cinmas.Description,
Logo = cinmas.Logo,
Name = cinmas.Name
}
};
return response.AsQueryable();
}
}
在第 4 步中,雖然表確實有 5 行,但沒有返回任何行。
那么如何解決這個問題呢?
我需要將自定義視圖 model CinimaViewModels
上的數據返回為IQueryable
,但未顯示任何內容。
如何解決這個問題?
更新:我檢查了這個以從 model 返回數據,它返回 5 行,如下所示:
var cinmas2 = _context.Cinemas.ToList();
但是從上面步驟 4 的視圖 model 來看,沒有返回任何內容。
如果要讀取數據庫中的數據,應該從dbcontext中讀取,而不是創建一個新的實例;
在你的 GetAllCinimas 方法中,你可以嘗試如下:
public IQueryable<CinimaViewModel> GetAllCinimas()
{
var response = _context.Cinema.Select(x => new CinimaViewModel() { Logo = x.Logo, Name = x.Name });
return response;
}
您可以使用 LINQ 查看與數據轉換相關的文檔
如果您還有其他問題,請顯示更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.