我正在使用ASP.NET MVC 4和C#。我编写代码来通过从数据库中检索数据来显示来自webgrid的数据。有效。但是,如果有任何不良情况如数据库损坏或其他东西,它将无法检索数据,所以我希望webgrid返回空列表或显示“没有员工数据”而不是抛出错误。我在webgrid中添加了if语句似乎不起作用。它仍然会引发错误:
“必须绑定数据源才能执行此操作。”
希望您能帮助解决我的代码,如下所示:
EmployeeController:
var employees = (IEnumerable<Employees>)Session["Employees"] ?? EmployeeService.LoadEmployees(Guid.Empty, string.Empty, null, null, string.Empty, "Error");
index.chstml
@grid.GetHtml(
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column(columnName: "ConvertedId", header: "Employee ID", format: (item) => string.IsNullOrEmpty(item.ConvertedId)?string.Empty:item.ConvertedId),
grid.Column(columnName: "Employee Code", header: "Vendor Name", format: (item) => string.IsNullOrEmpty(item.EmployeeCode)?string.Empty:item.EmployeeCode),
grid.Column(columnName: "Date", header: "Date", format: (item) => string.IsNullOrEmpty(item.Date.ToString())?string.Empty:item.Date.ToString()),
grid.Column(columnName: "Status", header: "Status", format: (item) => string.IsNullOrEmpty(item.Status)?string.Empty:item.Status),
))
答案 0 :(得分:0)
通过检查Index
值在Model
视图中创建一个条件声明,同时创建一个表,查找未找到员工数据的情况,见下文:
@model IEnumerable<Employees>
<div>
@if (Model.Any())
{
grid.GetHtml(
// Your existing code here
);
}
else
{
<div class="grid">
<table>
<thead>
<tr>
<th>Employee ID</th>
<th>Vendor Name</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" align="center">
No Employee Datafound
</td>
</tr>
</tbody>
</table>
</div>
}
</div>