【问题标题】:Return either a file OR an ajax alert in MVC在 MVC 中返回文件或 ajax 警报
【发布时间】:2011-09-07 23:58:32
【问题描述】:

假设我的主页上有一个包含多个选项的表单。其中之一是采用 customerID 的局部视图。如果 customerID 有效并且有产品,我会返回一个 CSV 文件,如下所示:

    public ActionResult CustomerProductsExport(string CustomerId)
    {

        var export = "\"ProductID\"\n";

        IEnumerable<int> products = CustomerFactory.GetProducts(CustomerId);

        export += string.Join("\n", products);

        var aFileContent = Encoding.ASCII.GetBytes(export);
        var aMemoryStream = new MemoryStream(aFileContent);
        return File(aMemoryStream, "text/plain",
                    string.Format("{0}.csv", CustomerId));

    }

但是,有几种情况会失败:客户 ID 不存在,或者他们没有产品。我只想返回一个 javascript 警报来指示这些情况中的任何一种。我已经尝试过 FormMethod.Get 和 .Post :

返回 Javascript("alert('foo');");

但这总是会产生一个文字字符串,而不是运行我的 javascript。如何在没有帖子的情况下获得我想要的行为或交付文件或发出 javascript 警报?我还尝试了提交按钮和 ActionLink... 相同的结果。

【问题讨论】:

    标签: c# ajax asp.net-mvc


    【解决方案1】:

    在这种情况下,我会返回表示结果的 JSON;如果成功,您将发出第二个请求以获取实际的文件资源。

    你会这样做:

    public ActionResult SomeMethod()
    {
        if(EverythingIsOk)
          return Json(new { IsError = false, Url = "http://someUrl/" });
    
        return Json(new { IsError = true, Error = "You're doing it wrong" });
    }
    

    您的客户端收到 Json,然后检查是否有错误。如果不是,那么它会获取 Url 并请求该资源(因此,下载文件)。

    【讨论】:

      【解决方案2】:

      如果您将内容类型设置为application/javascript,它应该可以工作

      public ActionResult CustomerProductsExport(string CustomerId)
      {
          var export = "\"ProductID\"\n";
          var products = CustomerFactory.GetProducts(CustomerId);
          if (products == null)
          {
              return new ContentResult { 
                  Content = "alert('Invalid customer id');",
                  ContentType = "application/javascript"
              };
          }
      
          export += string.Join("\n", products);
      
          var fileContent = Encoding.ASCII.GetBytes(export);
          var stream = new MemoryStream(fileContent);
          return File(stream, "text/plain",
                      string.Format("{0}.csv", CustomerId));
      
      }
      

      编辑

      JavascriptResult 使用过时的 application/x-javascript 标头,这可能是它无法按预期工作的原因。这就是上面的代码应该可以工作的原因。

      查看这些问题:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        • 2016-01-12
        • 2017-01-02
        • 2015-05-06
        相关资源
        最近更新 更多