如何将操作结果保存到文件?

时间:2011-05-26 07:13:24

标签: c# asp.net-mvc

如何在asp.net MVC中将操作结果保存到磁盘上的文件?

public void Test()
{
  var x = view();
  //save x as a file on disk
}

2 个答案:

答案 0 :(得分:1)

此方法(作为控制器类型的方法添加)将定位并触发视图并将视图结果作为字符串返回。

然后你可以拿着字符串并用它做你想做的事。

我将它用于电子邮件模板。

protected string ViewContent(string view, 
  string controller, ViewDataDictionary viewData)
{
  var routeData = new System.Web.Routing.RouteData(
    RouteData.Route, RouteData.RouteHandler);
  foreach (var item in RouteData.Values)
  {
    routeData.Values.Add(item.Key, item.Value);
  }
  //then overwrite the controller - not the action, though
  routeData.Values["controller"] = controller;

  var controllerContext = new ControllerContext(
    HttpContext, 
    routeData, 
    this);

  ViewEngineResult result = ViewEngines.Engines.FindView(
    controllerContext, 
    view, 
    null);

  string content = null;
  if (result.View != null)
  {
    using (StringWriter output = new StringWriter())
    {
      ViewContext viewContext = new ViewContext(
        controllerContext, result.View, viewData, TempData, output);

      viewContext.View.Render(viewContext, output);
      result.ViewEngine.ReleaseView(ControllerContext, viewContext.View);
      content = output.ToString();
    }
    return content;
  }
  else
    throw new InvalidOperationException("Can't find view");
}

然后我将这些重载添加到其他mvc方法中:

protected string ViewContent(string view)
{
  return ViewContent(view, (string)null);
}

protected string ViewContent(string view, string controller)
{
  return ViewContent(view, controller, (object)null);
}

protected string ViewContent(string view, object model)
{
  return ViewContent(view, (string)null, model);
}

protected string ViewContent(string view, 
  string controller, object model)
{
  if (string.IsWhitespaceOrNull(controller)
    controller = ControllerContext.
                 RouteData.GetRequiredString("controller");

  ViewDataDictionary viewData = 
    new ViewDataDictionary(ViewData) { Model = model };

  return ViewContent(view, controller, viewData);
}

答案 1 :(得分:-1)

Download Dynamically Generated File in ASP.NET MVC

只需添加

Response.AddHeader("Content-Disposition", "attachment;filename=myfile.csv"); 
ContentResult content = new ContentResult
        {
            ContentEncoding = System.Text.Encoding.UTF8,
            ContentType = "text/csv", Content="..." } return content; }