3
這裏有一個完整的初學者在C#MVC中需要一些幫助。 我堅持將viewmodel數據傳遞給PagedList。 我在做什麼錯?在控制器中,我得到 錯誤消息:如何將viewmodel傳遞給PagedList
無法隱式轉換類型「PagedList.IPagedList」到「PagedList.IPagedList」。存在明確的轉換(您是否缺少演員?)
我已經檢查了很多關於此主題的其他帖子,但無法解決我的問題。
這裏是我的視圖模型:
public partial class NaloziViewModel
{
public int IDNalozi { get; set; }
public int KlijentID { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime VremeStart { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime? VremeKraj { get; set; }
public int KilometrazaStart { get; set; }
public int? KilometrazaKraj { get; set; }
public virtual Klijent Klijent { get; set; }
public int? Page { get; set; }
}
Pagedclass
public class Pagedclass
{
public PagedList.IPagedList<NaloziViewModel> mylist { get; set; }
public int KilometrazaSum { get; set; }
public int VremeSum { get; set; }
}
控制器:
public ActionResult Index(int? page, DateTime? dateFrom, DateTime? dateTo, string klijentIme)
{
int pageSize = 10;
int pageNumber = (page ?? 1);
var naloziFilter = db.Nalozis.Include(n => n.Klijent).OrderByDescending(n => n.IDNalozi).Where(n => n.Obrisan == 0).ToPagedList(pageNumber,pageSize);
if (dateFrom != null && dateTo != null)
{
naloziFilter = naloziFilter.Where(n => n.Klijent.NazivKlijenta.Contains(klijentIme)).Where(n => n.VremeStart >= dateFrom).Where(n => n.VremeKraj <= dateTo).ToPagedList(pageNumber,pageSize);
TimeSpan vremeSum = new TimeSpan();
naloziFilter.Where(x => x.VremeKraj.HasValue).ToList().ForEach(x => vremeSum += x.VremeKraj.Value - x.VremeStart);
var model = new Pagedclass
{
mylist = naloziFilter,
KilometrazaSum = naloziFilter.Sum(n => n.KilometrazaKraj ?? 0) - naloziFilter.Sum(n => n.KilometrazaStart),
VremeSum = (vremeSum.Days*24)+vremeSum.Hours,
};
return View(model);
}
else
{
TimeSpan vremeSum = new TimeSpan();
naloziFilter.OrderByDescending(n => n.IDNalozi).Where(n => n.Obrisan == 0).Where(x => x.VremeKraj.HasValue).ToList().ForEach(x => vremeSum += x.VremeKraj.Value - x.VremeStart);
var model = new Pagedclass
{
mylist = naloziFilter,
KilometrazaSum = naloziFilter.Sum(n => n.KilometrazaKraj ?? 0) - naloziFilter.Sum(n => n.KilometrazaStart),
VremeSum = (vremeSum.Days * 24) + vremeSum.Hours
};
return View(model);
}
}
筆者認爲:
@model Pagedclass
@using PagedList;
@using PagedList.Mvc;
....
你從上查詢回收集'db.Nalozis'是'Nalozi'不是'NaloziViewModel'的集合。您需要將這些項目投影到'NaloziViewModel'。 – Jasen 2014-10-27 21:17:10
@Jasen 你能幫我解決這個問題嗎?不知道應該怎麼做。 – 2014-10-28 08:24:17
[這個問題的答案](http://stackoverflow.com/a/5392180/2030565)有一個投影的例子。該問題詢問[AutoMapper](https://github.com/AutoMapper/AutoMapper/wiki/Getting-started),這是一個幫助您處理這些投影的工具,因此您無需重複輸入這些內容。 – Jasen 2014-10-28 17:46:17