2014-01-22 79 views
0

我使用MVC 3和LINQ在asp.net to SQL中,我試圖導出我的WebGrid數據的Excel工作表的新手,但它的定義拋出錯誤:「System.Web.Helpers.WebGrid」不包含「RenderControl」

'System.Web.Helpers.WebGrid' does not contain a definition for 'RenderControl' and no extension method 'RenderControl' accepting a first argument of type 'System.Web.Helpers.WebGrid' could be found (are you missing a using directive or an assembly reference?) 

我發佈的代碼,所以你們可以幫我。 代碼:

控制器:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Helpers; 
using EmployeeAttendance_app.Models; 
using System.IO; 
using System.Web.UI.WebControls; 
using System.Web.Mvc.Html; 


namespace EmployeeAttendance_app.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewBag.Message = "Precise Technology Consultants"; 
      var DataContext = new EmployeeAtdDataContext(); 
      //var EmployeeAtd = DataContext.GetAttendance_Sp(); 
      IEnumerable<GetAtdRecord_SpResult> EmployeeAtd = DataContext.GetAtdRecord_Sp(null).ToList(); 
      return View(EmployeeAtd); 

     } 

     public ActionResult About() 
     { 
      return View(); 
     } 

     public ActionResult ViewData() 
     { 
      return View(); 
     } 

     public ActionResult ToExcel() 
     { 
      var DataContext = new EmployeeAtdDataContext(); 

      IEnumerable<GetAtdRecord_SpResult> EmployeeAtd = DataContext.GetAtdRecord_Sp(null).ToList(); 

      var grid = new WebGrid(EmployeeAtd, defaultSort: "EmplID"); 
      Response.ClearContent(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment; filename=AttendanceSheet.xls"); 
      Response.ContentType = "application/ms-excel"; 
      Response.Charset = ""; 
      System.IO.StringWriter sw = new System.IO.StringWriter(); 
      System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 
      grid.RenderControl(htw); 
      Response.Output.Write(sw.ToString()); 
      Response.Flush(); 
      Response.End(); 
      return RedirectToAction("Index"); 
     } 
    } 
} 

這裏是視圖,它應該dispaly數據,然後點擊導出應該導出文件 VIEW:

@using EmployeeAttendance_app.Models 



<div> 

@{ 

    var grid = new WebGrid(ViewData.Model, defaultSort: "EmplID"); 

} 

@grid.GetHtml() 

@using (Html.BeginForm("ToExcel","Home",FormMethod.Post)) 
{ 
    <button type="submit" >To Excel</button> 
} 
</div> 

回答

0

您應該爲您的數據參數:

var grid = new WebGrid(source: ViewData.Model, defaultSort: "EmplID"); 

此外源代碼需要類型爲IEnumerable<object>,因此如果您的Model類未實現IEnumerable<object>,則應更改它或指定模型的屬性以用作WebGrid助手的源數據。