lundi 29 juin 2015

MVC - Passing generic model to a method

I have a function FillPdf() which I am using to fill an editable pdf. For now I have defined its parameter type but I have three different forms each having different model so I want is my this FillPdf() receives the respective model and use its data.How to achieve this.

FillPdf.cs

  public static bool FillPdf(M2HDetail m2HUserDetails)
    {
        try
        {
            if (PdfFileSettingViewModel.M2HAuthorizationFormLocation == null)
                return false;
            var pdfReader = new PdfReader(PdfFileSettingViewModel.M2HAuthorizationFormLocation);
            var sb = new StringBuilder();
            foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
            {
                sb.Append(de.Key.ToString() + Environment.NewLine);
            }
            var newFile = Path.Combine(PdfFileSettingViewModel.TempFolderLocation, string.Format("{0}_{1}.pdf", "M2HForm",SessionItems.UserId));
            System.IO.File.Copy(PdfFileSettingViewModel.M2HAuthorizationFormLocation, newFile);

            var pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

            var pdfFormFields = pdfStamper.AcroFields;
            var totalFields = pdfFormFields.Fields.Count;

            var myParams = new List<string>();

            #region # SetPdfFields #

            pdfFormFields.SetField("Text1", m2HUserDetails.LastName);
            pdfFormFields.SetField("Text2", m2HUserDetails.FirstName);
            pdfStamper.FormFlattening = false;

            #endregion

            pdfStamper.Close();

            return true;

        }
        catch (Exception ex)
        {
            var files = System.IO.Directory.GetFiles(PdfFileSettingViewModel.TempFolderLocation);
            foreach (var file in files)
            {
                System.IO.File.Delete(file);
            }

            return false;
        }

    }

Caller function

 public ActionResult AuthorizationForm(M2HDetail model)
    {
      var isFillPdfSuccess = PdfFiller.FillPdf(model);
      return View();
     }

Now I want that I can use the same pdf method for my other form like this:

 public ActionResult AuthorizationFormHippa(HippaAuthForm model)
    {
      var isFillPdfSuccess = PdfFiller.FillPdf(model);
      return View();
     }

Also I want that my pdf method could have parameter as model like this:

  public static bool FillPdf(ModelForm model)
{
 }

Please suggest how to achieve this.As I can have more than 3 forms in future and each time I have to write the same method just with different parameter type.

Aucun commentaire:

Enregistrer un commentaire