首页 新闻 赞助 找找看

MVC3 Action重用

0
悬赏园豆:15 [已解决问题] 解决于 2014-05-12 10:10

在开发一个项目的时候,发现有几个Action基本架构是一样的,但是不懂怎么重用。

Action1:

 public ActionResult CountAllPrint(string dateS, string dateE)
        {
            if (string.IsNullOrEmpty(dateS))
                dateS = null;
            if (string.IsNullOrEmpty(dateE))
                dateE = null;
            ActiveCenterService service = new ActiveCenterService();
            MemoryStream ms = service.ActionCountExcel(dateS, dateE);
            if (ms != null)
            {
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Download.xls")); 
                Response.BinaryWrite(ms.ToArray()); 
                ms.Close();
                ms.Dispose();
                return new EmptyResult();
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('没有获取到Excel数据,重新获取!');history.back();</script>");
                return new EmptyResult();
            }
        }

Action2:

 public ActionResult CountDetailAllPrint(int id=0)
        {
            ActiveCenterService service = new ActiveCenterService();
            MemoryStream ms = service.ActionCountDetailAllExcel(id);
            if (ms != null)
            {
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Download.xls"));
                Response.BinaryWrite(ms.ToArray()); 
                ms.Close();
                ms.Dispose();
                return new EmptyResult();
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('没有获取到Excel数据,重新获取!');history.back();</script>");
                return new EmptyResult();
            }
        }

我想过了通过Action传值MemoryStream ,但是做不到,各位有什么好的方法吗?

听雨读诗的主页 听雨读诗 | 初学一级 | 园豆:47
提问于:2014-01-15 14:39
< >
分享
最佳答案
0

是啊,楼上说的好。你把需要的代码用一个方法去定义,需要的参数作为方法参数就行了啊。然后原代码调用方法

 访问修饰符 返回类型 方法名(所需参数) {
 ActiveCenterService service = new ActiveCenterService();
            MemoryStream ms = service.ActionCountExcel(dateS, dateE);
            if (ms != null)
            {
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Download.xls")); 
                Response.BinaryWrite(ms.ToArray()); 
                ms.Close();
                ms.Dispose();
                return new EmptyResult();
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('没有获取到Excel数据,重新获取!');history.back();</script>");
                return new EmptyResult();
            }
}
收获园豆:10
Cherbim | 菜鸟二级 |园豆:323 | 2014-01-15 22:58
其他回答(1)
0

把共用的代码放到一个函数里就可以了。

收获园豆:5
路过秋天 | 园豆:4787 (老鸟四级) | 2014-01-15 15:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册