代碼:無法分配/強制轉換的ViewData到變量,對象引用未設置
@{
....
var GotAllDetails = ViewData["GetAllDetails"] as List<PRJ.DetailViewsModel>;
....
}
和
@foreach (var goteem in GotAllDetails){Print my pretty list}
我已經做了很多的調試。我在var GetAllDetails
後面放了一個斷點,我可以確認ViewData["GetAllDetails"]
已正確填充。我正在類型化的模型具有與ViewData.
相同的價值名稱和類型,但是,不知何故,GotAllDetails
是null
。當頁面點擊我的foreach
它通過我
異常詳細信息:System.NullReferenceException:對象不設置到對象的實例。
根據要求,我會分享更多的代碼,但首先告訴我,如果我有任何明顯的錯誤。
編輯:每請求,這裏的指定計算機[ 「GetAllDetails」]
ViewData["GetAllDetails"] = getAllDetails.OrderBy(q => PadString(q.TaskDescription, ".")).ToList();
而且LINQ查詢
var getAllDetails =
(from m in _db.MyStandards.AsEnumerable()
join t in _db.Tasks on m.TaskId equals t.TaskId
join p in _db.Products on t.ProductId equals p.ProductId
join ce in _db.CompetencyElements on p.CompetencyElementId equals ce.CompetencyElementId
join comp in _db.Competencies on ce.CompetencyId equals comp.CompetencyId
join fu in _db.FunctionalUnitOfCompetences on comp.FunUnitOfCompetenceId equals fu.FunUnitOfCompetenceId
join c in _db.Careers on fu.CareerId equals c.CareerId
join rx in _db.RubricRefs on m.RubricStandardId equals rx.Id
where (t.TaskId == m.TaskId && m.Email == getUserById && p.ProductId == proId)
group new { t.TaskDescription, m.RubricStandardId, m.Comments }
by new
{
c.CareerDescription,
fu.FunUnitOfCompetenceDesc,
comp.CompetencyDescription,
ce.CompetencyElementdesc,
p.ProductDescription,
t.TaskDescription,
m.RubricStandardId,
m.Comments,
m.StandardId,
m.TaskId,
m.ActiveInd,
rx.RubricHexColor,
rx.RubricSymbol
} into g
select new
{
ActiveInd = g.Key.ActiveInd,
CareerDescription = g.Key.CareerDescription,
Comments = g.Key.Comments,
CompetencyDescription = g.Key.CompetencyDescription,
CompetencyElementdesc = g.Key.CompetencyElementdesc,
FunUnitOfCompetenceDesc = g.Key.FunUnitOfCompetenceDesc,
ProductDescription = g.Key.ProductDescription,
StandardId = g.Key.StandardId,
RubricHexColor = g.Key.RubricHexColor,
RubricStandardId = g.Key.RubricStandardId,
RubricSymbol = g.Key.RubricSymbol,
TaskDescription = g.Key.TaskDescription,
TaskId = g.Key.TaskId,
});
和模型
public class DetailViewsModel
{
public string ActiveInd { get; set; }
public string CareerDescription {get;set;}
public string Comments {get;set;}
public string CompetencyDescription {get;set;}
public string CompetencyElementdesc {get;set;}
public string FunUnitOfCompetenceDesc {get;set;}
public string ProductDescription {get;set;}
public int StandardId {get;set;}
public string RubricHexColor {get;set;}
public int RubricStandardId {get;set;}
public string RubricSymbol {get;set;}
public string TaskDescription {get;set;}
public int TaskId {get;set;}
}
「正確填充」意味着ViewData [「GetAllDetails」]真的返回一個List?如果返回的對象是不同類型的,則'as'運算符返回'null'。 –
據我所知,是的。 ViewData來自一個LINQ查詢,並且我確信我所輸入的模型具有與所述查詢輸出相同的值。 – UIDAlexD
我的問題不是它具有相同的屬性。你說你調試過它,所以你可以再次調試並確定實際類型。正如我所說,如果它不是正確的類型,「GotAllDetails」將爲空。如果是這種情況,則需要進行某種轉換。 –