在开发一个项目的时候,发现有几个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 ,但是做不到,各位有什么好的方法吗?
是啊,楼上说的好。你把需要的代码用一个方法去定义,需要的参数作为方法参数就行了啊。然后原代码调用方法
访问修饰符 返回类型 方法名(所需参数) { 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(); } }
把共用的代码放到一个函数里就可以了。