当我尝试显示viewbag的值时,我收到异常。我加入了两个表并使用Linq将该数据存储在viewbag中。
这是我的控制器操作方法
public ActionResult HRSeparationDetails()
{
//List<trnEsSeparationDetail> separationlist = (from list in db.trnEsSeparationDetails
// select list).ToList();
ViewBag.SeparationList = (from list in db.trnEsSeparationDetails
join R in db.mstEsEmpReasonForSeparations
on list.ReasonForSeperationId equals R.intSeperationId
select new
{
intEmployeeId = list.intEmpId,
ReasonForSeparation = R.txtReasonForSeperation,
ResiganationDate = list.dtResignationDate,
RelievingDate = list.dtRequestedRelievingDate,
SeparationRemarks = list.txtRemark
}).ToList();
return View();
}
这是我的浏览页
@model IEnumerable<EMPApp.Models.trnEsSeparationDetail>
@{
ViewBag.Title = "HRSeparationDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>HRSeparationDetails</h2>
<div>
@if (ViewBag.SeparationList == null)
{
<div style="color:green"><h3>@ViewBag.SeparationerrorMessage</h3></div>
}
else
{
<table class="grid" cellpadding="0" cellspacing="0">
<tr>
<th>
<b>Employee Id</b>
</th>
@*<th>
<b>ReasonForSeparationId</b>
</th>*@
<th>
<b>Reason For Separation</b>
</th>
<th>
<b>Resignation Date</b>
</th>
<th>
<b>Relieving Date</b>
</th>
<th>
<b>Separation Remarks</b>
</th>
</tr>
@foreach (var item in ViewBag.SeparationList)
{
<tr>
<td>
@item.intEmployeeId
@*@{
Session["SeparationEmpId"] = item.intEmpId;
}
@Html.ActionLink(Session["SeparationEmpId"].ToString(), "EmployeeDashboard", "HRAdmin", new { id = @item.intEmpId }, null)*@
</td>
@*<td>
@item.ReasonForSeperationId
</td>*@
<td>
@item.ReasonForSeparation
</td>
<td>
@item.ResiganationDate
</td>
<td>
@item.RelievingDate
</td>
<td>
@item.SeparationRemarks
</td>
</tr>
}
</table>
}
任何帮助将不胜感激。感谢..
答案 0 :(得分:0)
ViewBag是一个动态对象,您可以将该属性设置为匿名对象的集合。在你的foreach循环中
@foreach (var item in ViewBag.SeparationList)
项为typeof object
,object
没有属性intEmployeeId
(或您在匿名对象中定义的任何其他属性)。处理此问题的一种方法是使用要显示的属性创建视图模型
public class SeparationDetailVM
{
public int intEmployeeId { get; set; }
public DateTime ResiganationDate { get; set; }
....
}
并在控制器中
var details = (from list in ....
select new SeparationDetailVM
{
intEmployeeId = list.intEmpId,
ResiganationDate = list.dtResignationDate,
....
}).AsEnumerable();
return View(details); // no need for ViewBag
并在视图中
@model IEnumerable<YourAssembly.SeparationDetailVM>
....
@foreach (var item in Model)
{
....
<td>@item.intEmployeeId</td>
<td>@item.ResiganationDate</td>
....
}