【问题标题】:mvc 4 - how to return empty list from webgrid instead of throwing errormvc 4 - 如何从 webgrid 返回空列表而不是抛出错误
【发布时间】:2014-02-21 09:59:20
【问题描述】:

我正在使用 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),

        ))

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor webgrid


    【解决方案1】:

    通过检查Model 值在您的Index 视图中创建一个条件语句,还为未找到员工数据的情况创建一个表,见下文:

    @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>
    

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多