初学者到MVC 4:需要从外部或其他类调用方法

时间:2013-11-10 08:47:21

标签: c# asp.net-mvc asp.net-mvc-4

我是MVC 4的新手。我有一个场景,我需要在单独的类中定义一组方法并在控制器中调用所有这些方法。这样我就能处理与视图不同的功能。

以下是我的代码示例....请查看。

我在控制器下添加了一个新的类文件,并定义了如下方法:

 public void Convert(ConvertFileOutputType outputType, FileInfo inFile, DirectoryInfo        outFolder, int timeout,
        int topMargin, int bottomMargin, int leftMargin, int rightMargin)
    {
       switch (outputType)
        {
            case ConvertFileOutputType.Pdf:
                break;
            default: break;
            // throw new    ConvertFileException(Properties.Resources.OutputTypeNotSupportedWordPerfect);
        }
        if (converter == null)
        {
            //converter.LicenseKey = "";
            converter = new PdfConverter();
            converter.LicenseKey = "";
            converter.PdfDocumentOptions.LiveUrlsEnabled = false;
            converter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter;
            converter.PdfDocumentOptions.TopMargin = topMargin;
            converter.PdfDocumentOptions.BottomMargin = bottomMargin;
            converter.PdfDocumentOptions.LeftMargin = leftMargin;
            converter.PdfDocumentOptions.RightMargin = rightMargin;
            converter.AvoidImageBreak = true;
        }
        converter.PdfDocumentInfo.AuthorName = "FileConvert";
        converter.PdfDocumentInfo.Title = inFile.Name;
        converter.PdfDocumentInfo.CreatedDate = DateTime.Now;
        converter.SavePdfFromHtmlFileToFile(inFile.FullName, outFolder + "\\" + inFile.Name + ".pdf");
    }

我想在控制器方法中调用上面的方法.... 我盲目地编写代码......

  public string UploadAsPDF(HttpPostedFileBase fileData)
     {
         var fileName = this.Server.MapPath("~/uploads/" +     System.IO.Path.GetFileName(fileData.FileName));
         fileData.SaveAs(fileName);


        Convert(outputType, inFile,outFolder,timeout, topMargin, bottomMargin, leftMargin, rightMargin);

         return "OK"; 
     }

每当我尝试构建其类型时,都会被用作方法 请建议......

1 个答案:

答案 0 :(得分:0)

如果Convert方法位于名为Converters的类中,则需要instantiate该类,然后调用Convert ....

public Converters {
   public void Convert(...);
} 

然后你会像这样使用......

public string UploadAsPDF(HttpPostedFileBase fileData)
     {
         var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName));
         fileData.SaveAs(fileName);


        var converters = new Converters();
        converters.Convert(outputType, inFile,outFolder,timeout, 
                           topMargin, bottomMargin, leftMargin, rightMargin);

         return "OK"; 
     }