jqgrid + EF + MVC:是否可以使用总是相同的控制器操作在excel中导出? [英] jqgrid + EF + MVC: Is it possible to export in excel, using always the same controller action?

查看:154
本文介绍了jqgrid + EF + MVC:是否可以使用总是相同的控制器操作在excel中导出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有EF 4 + MVC3 的 jqgrid(标准)。我想实现excel导出,如果可能,使用与填充网格相同的动作控制器。
我想知道是否可能/逻辑地传递一个附加参数,例如。你会建议我的哪种方法?
我提出这个问题,因为我仍然要实现excel导出,我想要优化/重用代码,如果可能的话。

I am using jqgrid (standard) with EF 4 + MVC3. I'd like to implement excel export and if possible using the same action controller used to populate the grid. I wonder if is it possible / logical to pass an additional parameter, for example. Which method you would suggest me? I ask this question because I am still approaching to implement excel export and I'd like to optimize / re-use code, if possible.

要生成excel,我希望使用这个库,它有三种类型输出并允许定义标题。请告诉我,如果你觉得我的目的是有效的。

To generate excel, I'd like to use this library by Dr Stephen Walther, which has three types of output and allows to define headers too. Please tell me if you find it valid for my purpose.

关于jqgrid代码,我发现这个有趣的答案 Oleg,但我不明白是否可以适用于我的需要。

About the jqgrid code, I found this interesting answer by Oleg, but I do not understand if could be applied to my needs.

不幸的是,到目前为止,我只找到零件的解决方案,用于EF MVC的excel导出,但没有解决方案或完整的示例...

Unfortunately, by now I only found parts of solutions for excel export with EF MVC, but no solution or complete examples...

这是包含我的jqgrid 的_Index部分视图 p>

Here's the _Index partial view containing my jqgrid

  <table id="mygrid"></table>
  <div id="pager2"></div>

  jQuery("#mygrid").jqGrid({
url:'controller/jqIndex',
datatype: "json",
colNames:['id','field1', ...],
colModel:[
    {name:'id',index:'id', width:55},
    {name:'field1',index:'field1', width:90},
            ...
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"modal jquery + jqgrid test"}); 
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});

//TODO
???
...some code to call the controller action with the `excel` parameter set `true`

CONTROLLER(基于 OLEG的实现

CONTROLLER (BASED ON OLEG'S IMPLEMENTATION)

     public ActionResult jqIndex(string sidx, string sord, int page, int rows, bool _search, string filters, bool excel) // note the excel parameter <<
       {
        var context = new TManagerContext();
        var objectContext = context.ObjectContext();

        var set = objectContext.CreateObjectSet<Ticket>();
        var serializer = new JavaScriptSerializer();

        Filters f = (!_search || string.IsNullOrEmpty(filters)) ? null : serializer.Deserialize<Filters>(filters);
        ObjectQuery<Ticket> filteredQuery = (f == null ? (set) : f.FilterObjectSet(set));

        filteredQuery.MergeOption = MergeOption.NoTracking; // we don't want to update the data


        int totalRecords = filteredQuery.Count();

        var pagedQuery = filteredQuery.Skip("it." + sidx + " " + sord, "@skip",
                                    new ObjectParameter("skip", (page - 1) * rows))
                             .Top("@limit", new ObjectParameter("limit", rows));

        int pageIndex = Convert.ToInt32(page) - 1;
        int pageSize = rows;

        int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

        var queryDetails = (from e in pagedQuery
                            select new
                            {
                                e.TicketID,
                                e.field1,
                                ...
                            }).ToList();

        var result = new
        {
            total = totalPages,
            page = page,
            records = totalRecords,
            rows = (from e in queryDetails
                    select new
                    {
                        id = e.TicketID,
                        cell = new string[]
                        {
                            e.field1,
                            ...
                        }

                    }).ToArray()
        };

         if (excel) {
            ExportExcel(result); // if possible, pass filter parameters too, column order, etc...
         }

        return Json(result, JsonRequestBehavior.AllowGet);
    }

请问如果问题可能是愚蠢的,我只是一个(爱好者)初学者。

感谢您的宝贵帮助!

Thanks for your precious help! Best Regards

推荐答案

Larry - 几条评论。

Larry - A few comments.


  1. 您不应该在控制器中做这么多的逻辑。将所有
    的业务逻辑移动到另一个类/服务。那么你的动作
    方法将只是几行。一个简单的例子







public JsonResult jqIndex(string sidx, string sord, int page, int rows, 
                          bool _search, string filters){
        return JSON(this.GridQueryService.GetJQGrid(sidx,sord,page,rows,_search,filters), JsosnRequestBehavior.AllowGet);
        }

2.我知道你不想重复代码(哪一点1帮助),但是这里有很多参数和事情根本不适用于Excel(页面,行)。

2.I know you don't want to repeat code (which point 1 helps) but there are many parameters and things here that simply do not apply to Excel (page, rows).

3.调用布尔参数来更改函数的功能凌乱快假设您现在需要将更多/更少的数据传递到Excel文件,现在您已经在整个地方拥有嵌套条件,而单元测试只会令人沮丧。

3.Passing boolean parameters to change how things function can get messy fast. Lets assume that you now need to pass more/less data to the Excel file, now you have nested conditions all over the place and Unit Testing would just be crappy.

4一个excel动作方法应该有一个FileResult返回类型,而不是一个
的JSON结果(我猜他们都是动作结果,但这样会使你的意图在你的代码中更加清晰,你的定义应该是这样的, / p>




4.An excel action method will should have a FileResult return type, not a JSON result (I guess they are all action results, but this makes your intention all the more clear in your code. Your definition should be something like

public FileResult GetExcelFile(string sidx, string sord, bool _search, 
                               string filters){
              //do stuff to return Excel
        }

如果您在第一点创建您的服务,方式有两种返回不同项目的方法,但共享一个常见的查询/搜索库功能,那么在遵循单一责任原则的同时,您确实保持干燥。此服务的示例可能(非常粗略的例子,应该给你一些需要考虑的事情):

If you create your Service in point one in such a way that you have two methods that return different items, but share a common query/search base function, then you are really staying Dry while following the Single Responsibility Principle. An example of this service might be (very rough example, should give you some things to think about):

public class GridQueryService{
   public YourViewModel GetJQGrid(sidx, page, row, _search, filters){
      //Get the base data 
      var myData = this.GetGridData(sidx, _search, filters);
      //Create your view model and return it back to controller
} 
   public StreamWriter GetExcelFIle(sidx, _search, filters){
      //Get the base data 
      var myData = this.GetGridData(sidx, _search, filters);
      //Create your Excel file and return it to the controller
}

    private ObjectQuery<Ticket> GetGridData(string sidx, bool _search, string filters){
     //do your data grabbing here - you never return the raw data back to anything outside
     //of this service, so it should be ok to make private
}

}

这篇关于jqgrid + EF + MVC:是否可以使用总是相同的控制器操作在excel中导出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆