jqGrid的EF + + MVC:是否有可能在Excel导出,始终使用相同的控制器行动? [英] jqgrid + EF + MVC: Is it possible to export in excel, using always the same controller action?

查看:192
本文介绍了jqGrid的EF + + MVC:是否有可能在Excel导出,始终使用相同的控制器行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的的jqGrid(标准)与EF 4 + MVC3 。我想实现使用用于填充网格同样的动作控制器Excel导出如果可能的话。
我不知道是否有可能/逻辑传递一个额外的参数,例如。哪种方法你有什么建议吗?
我问这个问题,因为我仍然接近实现Excel导出,我想为优化/再利用 code,如果可能的话。

要生成EXCEL,我想使用<一个href=\"http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx\"相对=nofollow>这个库通过斯蒂芬·瓦尔特博士,其中有三个类型的输出,并允许定义头了。请告诉我,如果你发现它适用于我的目的。

关于jqGrid的code,我发现由奥列格这有趣的答案,但我不,如果能理解适用于我的需求。

不幸的是,目前我只发现Excel导出与EF MVC解决方案的一部分,但没有解决方案或完整的例子...

这里包含_index局部视图我的jqGrid

 &LT;表ID =mygrid&GT;&LT; /表&gt;
  &LT; D​​IV ID =pager2&GT;&LT; / DIV&GT;  jQuery的(#mygrid)。jqGrid的({
网址:控制器/ jqIndex',
数据类型:JSON
colNames:['身份证','字段1',...]
colModel:
    {名称:'身份证',索引:'ID',宽度:55},
    {名:字段1,索引:字段1,宽度:90},
            ...
]
的rowNum:10,
rowList:[10,20,30]
呼叫器:#pager2',
sortname:'ID',
viewrecords:真实,
排序顺序:递减,
标题:情态的jQuery + jqGrid的测试});
。jQuery的(#列表2)的jqGrid('navGrid','#pager2',{编辑:假的,加:假的,德尔:假});//去做
???
......有些code调用与`TRUE`了`excel`参数设置控制器动作

控制器(基于<一个href=\"http://stackoverflow.com/questions/5500805/asp-net-mvc-2-0-implementation-of-searching-in-jqgrid/5501644#5501644\">OLEG'S实施)

 公众的ActionResult jqIndex(字符串SIDX,串SORD,诠释页,INT行,布尔_search,字符串过滤器,布尔EXCEL)//注意Excel的参数&LT;&LT;
       {
        VAR语境=新TManagerContext();
        VAR的ObjectContext = context.ObjectContext();        VAR套= objectContext.CreateObjectSet&LT;门票&GT;();
        VAR串行=新的JavaScriptSerializer();        过滤器F =(!_search || string.IsNullOrEmpty(过滤器))?空:serializer.Deserialize&LT;滤波器及GT;(过滤器);
        的ObjectQuery&LT;门票&GT; filteredQuery =(F == NULL(SET):f.FilterObjectSet(套));        filteredQuery.MergeOption = MergeOption.NoTracking; //我们不想更新数据
        INT总记录= filteredQuery.Count();        VAR pagedQuery = filteredQuery.Skip(吧。+ SIDX ++ SORD@skip
                                    新ObjectParameter(跳过,(第 - 1)*行))
                             .TOP(@极限,新的ObjectParameter(限制,行));        INT的PageIndex = Convert.ToInt32(页) - 1;
        INT的pageSize =行;        INT总页数=(int)的Math.Ceiling((浮点)总记录/(浮动)的pageSize);        VAR queryDetails =(从E在pagedQuery
                            新选择
                            {
                                e.TicketID,
                                e.field1,
                                ...
                            })了ToList()。        VAR的结果=新
        {
            总=总页数,
            页=页,
            记录=总记录,
            行数=(从E在queryDetails
                    新选择
                    {
                        ID = e.TicketID,
                        电池=新的String []
                        {
                            e.field1,
                            ...
                        }                    })。ToArray的()
        };         如果(EXCEL){
            ExportExcel(结果); //如果可能的话,带通滤波器的参数太多,列顺序,等等。
         }        返回JSON(结果,JsonRequestBehavior.AllowGet);
    }

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

感谢您​​的precious帮助!
*的此致的*


解决方案

拉里 - 一些看法。


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


 公共JsonResult jqIndex(字符串SIDX,串SORD,诠释页,INT行,
                          布尔_search,字符串过滤器){
        返回JSON(this.GridQueryService.GetJQGrid(SIDX,SORD,页,行,_search,过滤器),JsosnRequestBehavior.AllowGet);
        }

2.我知道你不想重复code(这点帮助1),但也有很多参数,这里的东西,根本不适用到Excel(页,行)。

3.Passing布尔参数来改变事物的功能如何能得到凌乱快。让我们假设你现在需要更多/更少的数据传递到Excel文件,现在你已经嵌套条件所有的地方和单元测试也只是蹩脚的。

4.An Excel的操作方法应该有一个FileResult返回类型,而不是一个
    JSON结果(我猜他们是一切行动的结果,但是这使得你的意图更加明确在code,你的定义应该是这样


 公共FileResult GetExcelFile(字符串SIDX,串SORD,布尔_search,
                               字符串过滤器){
              //做的东西返回Excel中
        }

如果您在你有两个方法,返回不同的项目,这样的方式创建你在一点一点服务,但都有一个共同的查询/搜索库函数,那么你真的保持干爽,而之后的单一职责原则。这种服务的一个例子可能是(非常粗略的例子,应该给你一些事情要考虑):

 公共类GridQueryService {
   公共YourViewModel GetJQGrid(SIDX,页,行,_search,过滤器){
      //获取基础数据
      VAR的myData = this.GetGridData(SIDX,_search,过滤器);
      //创建您的视图模型,然后返回到控制器
}
   公众的StreamWriter GetExcelFIle(SIDX,_search,过滤器){
      //获取基础数据
      VAR的myData = this.GetGridData(SIDX,_search,过滤器);
      //创建您的Excel文件,并返回到控制器
}    私人的ObjectQuery&LT;门票&GT; GetGridData(字符串SIDX,布尔_search,字符串过滤器){
     //做你的数据在这里抓 - 你永远不返回原始数据回任何东西之外
     //这个服务,所以它应该确定为私人
}}

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.

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.

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

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

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 (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);
    }

Please sorry if the question could be silly, I am just a (enthusiast) beginner.

Thanks for your precious help! *Best Regards*

解决方案

Larry - A few comments.

  1. You shouldn't be doing that much logic in your controller. Move all of that business logic to another class/service. Then your action method would be just a few lines. A quick example


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.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.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.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天全站免登陆