MVC3 Razor view not rendering dynamically added controls on postback - asp.net-mvc-3

I have to upload selected files and display these files as links on post back.
In my view I am adding each of the uploaded files as links using
#if (Model.IncidentLogInfoDetails.AttachmentCollection.AttachmentItemCollection.Any())
{
foreach (EML.Container.Attachment attachmentItem in Model.IncidentLogInfoDetails.AttachmentCollection.AttachmentItemCollection)
{
#Html.ActionLink(attachmentItem.FileName, "testing")
}
}
this is my controller action:
public ActionResult UploadingFiles(HttpPostedFileBase imageFile)
{
// Converting to Attachment object
Attachment fileAttachment = new Attachment();
fileAttachment.FileName = "imageFile.FileName";
fileAttachment.ContentType = imageFile.ContentType;
fileAttachment.SizeInBytes = imageFile.ContentLength;
using (MemoryStream ms = new MemoryStream())
{
imageFile.InputStream.CopyTo(ms);
fileAttachment.BinaryData = ms.GetBuffer();
}
IncidentDetails incidentDetails = new IncidentDetails();
incidentDetails.IncidentLogInfoDetails = new IncidentLogInfo();
incidentDetails.IncidentLogInfoDetails.AttachmentCollection.AttachmentItemCollection = new List<Attachment>();
incidentDetails.IncidentLogInfoDetails.AttachmentCollection.AttachmentItemCollection.Add(fileAttachment);
return View("FileUploadingTest", incidentDetails);
}
My problem is that even though the loop is getting executed and Action links are created ( on debugging), they are not displayed after post back. What am I missing ?

Related

.NET Core 3.1 convert to .NET 6 controller download method fails for no view

I converted a .NET Core 3.1 project to .NET 6 and now the download method produces this error:
System.InvalidOperationException: The view 'ExcelDownload' was not found. The following locations were searched:...
This is the method:
public IActionResult ExcelDownload(string TIDList)
{
// ...
// ...
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content, contentType, fileName);
}
}
There has never been a view for this method and it worked with .NET Core 3.1. What's different with .NET 6 that causes this to look for a view?
Using the ClosedXML NuGet to create the Excel file.
Thanks!
Hi you can try FileContentResult
public async Task<FileContentResult> ExcelDownload(string TIDList)
{
var fileProvider = new FileExtensionContentTypeProvider();
if (!fileProvider.TryGetContentType($"{fileName.FileName}{fileName.Extension}", out string contentType))
{
contentType = fileName.Extension.RemoveDot();
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return new FileContentResult(content, contentType)
{
FileDownloadName = fileName
};
}
}

authorization required when create pdf file

I am trying to generate pdf file using c# web api using the following code :
i have tried to change in the web.config but it didn't help.
[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
I expected download pdf directly to my local disk but non worked.

Develop Outlook add-in to upload attachments

I want to develop Office Outlook Plug-in to upload email message attachments if it exceeds for example 20 MB to OneDrive or SharePoint Online and add links for attachments to the message body while sending.
I need some guide to start, just show me the way and I'll walk it.
Update:
I've developed a part but once code reach clientContext.ExecuteQuery(); outlook crash.
private void ApplicationOnItemSend(object item, ref bool cancel)
{
var mailItem = item as Outlook.MailItem;
//Upload to SharePoint
foreach (Outlook.Attachment attachment in mailItem.Attachments)
{
if (IsAttachmentExceedLimit(attachment))
{
byte[] attachmentData = null;
// this is a standard attached object
attachmentData = attachment.PropertyAccessor.GetProperty(PrAttachDataBin) as byte[];
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(attachmentData, 0, attachmentData.Length);
theMemStream.Position = 0;
try
{
//Upload attachment to SharePoint Online
bool overwrite = Settings.Default.Overwrite;
using (ClientContext clientContext = ClaimClientContext.GetAuthenticatedContext(Settings.Default.SharePointSiteUrl))
{
var web = clientContext.Web;
var list = web.Lists.GetByTitle(Settings.Default.SharePointFolder);
var newFileFromComputer = new FileCreationInformation
{
Content = attachmentData,
Url = attachment.FileName
};
var uploadedFile = list.RootFolder.Files.Add(newFileFromComputer);
clientContext.Load(uploadedFile);
clientContext.RequestTimeout = 360000000;
clientContext.ExecuteQuery();
}
//Add Link for attachment
mailItem.HTMLBody += Settings.Default.SharePointSiteUrl + Settings.Default.SharePointFolder +
attachment.FileName + Environment.NewLine;
//Delete attachement from mail message
mailItem.Attachments.Remove(attachment.Index);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Note:
I don't have any experience in VSTO.

How to Generate pdf of details view in mvc 3

I just want to generate a pdf document of the details presents in view on button click.
In order to generate a PDF file you will need some third party library as this functionality is not built-in the .NET framework. iTextSharp is a popular one.
So for example you could write a custom action result:
public class PdfResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = "test.pdf",
};
response.AddHeader("Content-Disposition", cd.ToString());
using (var doc = new Document())
using (var writer = PdfWriter.GetInstance(doc, response.OutputStream))
{
doc.Open();
doc.Add(new Phrase("Hello World"));
}
}
}
and then have your controller action return this result:
public class HomeController : Controller
{
public ActionResult Index()
{
return new PdfResult();
}
}

Convert PartialView Html to String for ITextSharp HtmlParser

I've got a partial view, i'm trying to use ITextSharp to convert the html to pdf. How can I convert the html to string so I can use ItextSharps HtmlParser?
I've tried something like this with no luck...any ideas?:
var contents = System.IO.File.ReadAllText(Url.Action("myPartial", "myController", new { id = 1 }, "http"));
I have created a special ViewResult class that you can return as the result of an Action.
You can see the code on bitbucket (look at the PdfFromHtmlResult class).
So what it basically does is:
Render the view through the Razor engine (or any other registered engine) to Html
Give the html to iTextSharp
return the pdf as the ViewResult (with correct mimetype, etc).
My ViewResult class looks like:
public class PdfFromHtmlResult : ViewResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(this.ViewName)) {
this.ViewName = context.RouteData.GetRequiredString("action");
}
if (this.View == null) {
this.View = this.FindView(context).View;
}
// First get the html from the Html view
using (var writer = new StringWriter()) {
var vwContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer);
this.View.Render(vwContext, writer);
// Convert to pdf
var response = context.HttpContext.Response;
using (var pdfStream = new MemoryStream()) {
var pdfDoc = new Document();
var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();
using (var htmlRdr = new StringReader(writer.ToString())) {
var parsed = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(htmlRdr, null);
foreach (var parsedElement in parsed) {
pdfDoc.Add(parsedElement);
}
}
pdfDoc.Close();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", this.ViewName + ".pdf");
byte[] pdfBytes = pdfStream.ToArray();
response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
}
}
}
}
With the correct extension methods (see BitBucket), etc, the code in my controller is something like:
public ActionResult MyPdf(int id) {
var myModel = findDataWithID(id);
// this assumes there is a MyPdf.cshtml/MyPdf.aspx as the view
return this.PdfFromHtml(myModel);
}
Note: Your method does not work, because you will retrieve the Html on the server, thereby you loose all cookies (=session information) that are stored on the client.

Resources