I have a view which shows a list of xml files in a directory. Also i have a button which would display the content of the file name selected in the browser. Currently its showing the content in a the same tab. But i want to display it in a new tab of the browser..
for example if i select two file names from the list, then it should open different tab for both the files..
Please find the code below.
public ActionResult ViewFile(string[] Name)
{
byte[] ImageData = null;
for (int i = 0; i < Name.Length; i++)
{
string filepath = holdpath + #"\" + Name[i];
string result;
using (StreamReader streamReader = new StreamReader(filepath))
{
result = streamReader.ReadToEnd();
}
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Paragraph paragraph = new Paragraph();
paragraph.Add(result);
document.Add(paragraph);
document.Close();
ImageData = memoryStream.ToArray();
}
}
Response.AppendHeader("Content-Disposition", "inline; filename=MyFile.pdf");
return File(ImageData, "application/pdf");
}
Please note that i am using itextsharp because the file also needs to be downloaded as pdf if required
I have added the View here
#model IEnumerable<FileInfo>
#{
ViewBag.Title = "files";
}
<h2>Held files</h2>
#using (Html.BeginForm())
{
<div style="border:solid;width:100%;overflow-x:auto;">
<table align="center" style="width:100%">
<thead>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (FileInfo file in Model)
{
<tr>
<td>
<input type="checkbox" name="Name" value="#file.Name" />
#file.Name
</td>
<td>
#Html.ActionLink("View", "ViewFile", "HoldFiles", new { Name = file.Name },
new { #class = "btn btn-primary btn-sm", target = "_blank" })
</td>
</tr>
}
</tbody>
</table>
</div>
}
In your view, put target="_blank" on your anchor element.
For example:
Open in new tab
or if using razor:
#Html.ActionLink("Text", "ActionMethodName", "ControllerName", new { id = Model.Id }, new { #class = "btn btn-primary btn-sm", target = "_blank" })
Related
now my content is a one line but I want to new content is new line after the point(.)
.cs
[HttpGet]
public async Task<ActionResult> Career()
{
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = client.GetAsync("https://localhost:0000/Home/DisplayVacancyData").Result;
if (responseMessage.IsSuccessStatusCode)
{
//data = await responseMessage.Content.ReadAsAsync();
//List<Vacancy> products = await responseMessage.Content.ReadAsAsync<List<Vacancy>>();
string result = await responseMessage.Content.ReadAsStringAsync();
List<Vacancy> vaca = JsonConvert.DeserializeObject<List<Vacancy>>(result);
ViewBag.message = vaca + "<br />";
return View("Career",vaca);
}
return View();
}
.cshtml
<table class="table table-striped border">
<thead>
<tr>
<th>Vacancy Title</th>
<th>Vacancy Position</th>
<th>Vacancy Experience</th>
<th>Vacancy Jobdescription</th>
<th>Vacancy RequiredSkil</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var carr in Model)
{
//string newline = "\n";
<tr>
<td>#carr.vacancytitle</td>
<td>#carr.vacancyposition</td>
<td>#carr.vacancyexperience</td>
#*if()*#
<td>#carr.vacancyjobdescription#*<text> & nbsp;</ text >*#</td>
<td>#carr.vacancyrequiredskill</td>
<td>
#Html.ActionLink("Apply for Job", "ApplyForJob")
</td>
</tr>
}
</tbody>
</table>
means after point new content in separate line
logic is first find the point(.) in line then after add a new line
string newline = "\n";
if(carr.vacancyjobdescription)
{
//issue is here how to find out point in line
and then add a <text>newline</text>
}
what I am trying - main issue is how to find the point
<td>
#if (carr.vacancyjobdescription != null)
{
#carr.vacancyjobdescription
<text> </text>
}
</td>
<td>
#{
string skillHtml = #carr.vacancyrequiredskill;
skillHtml = skillHtml.Replace(".", "</br>");
}
#*Here we gonna display the html*#
#Html.Raw(skillHtml)
</td>
#{string data = "Hello. This is Test. Yo";
data= data.Replace(".", "</br>");}
#*Then to display your value use...*#
#Html.Raw(data)
My model have List products which get from database.
When index view loaded, i get the variable from input of user, then model get varible, and return view OutputTableAsync. After view loaded, i click link "Export Excel", in debug mode, List products is null.
My view:
<body>
#if (Model != null)
{
var products = Model.products.Products;
Export Excel
<table border="1" style="width: 100%">
<thead>
<tr>
<th>Model</th>
<th>Price</th>
<th>Link</th>
<th>ImageUrl</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.products.SortProduct())
{
<tr id="i">
<td align="center">#product.Model</td>
<td align="center">#product.FormatPrice()</td>
<td align="center">#product.Link</td>
<td align="center"><img src="#product.ImageUrl" style="width : 200px; height:200px ;" id="#product.ImageUrl" /></td>
</tr>
}
</tbody>
</table>
}
</body>
ExportToExcel method in controller:
public void ExportToExcel(List<Product> products)
{
ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Products");
ws.Cells["A1"].Value = "Model";
ws.Cells["B1"].Value = "Price";
ws.Cells["C1"].Value = "Link";
ws.Cells["D1"].Value = "ImageLink";
int rowstart = 2;
foreach(var item in products)
{
ws.Cells[string.Format("A{0}", rowstart)].Value = item.Model;
ws.Cells[string.Format("B{0}", rowstart)].Value = item.Price;
ws.Cells[string.Format("C{0}", rowstart)].Value = item.Link;
ws.Cells[string.Format("D{0}", rowstart)].Value = item.ImageUrl;
rowstart++;
}
ws.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelFile.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
According to accepted answer here you can not pass complex type through Url.Action
I would pass serialized version of object in this situation.
I have a list of items that I pull from a database and at the same time I want the user to enter the quantity issued.
My problem is that after I click the button print/issue the amount in the database for quantity issued is 0.
I have added a TextBox for the user to enter the value. Not sure if what I have here is correctly done.
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
View
if (#Model.items.Count > 0)
{
foreach (var issueditem in #Model.items)
{
<tr>
<td class="col-md-4">#issueditem.itemNumber</td>
<td class="col-md-4">#issueditem.description</td>
<td class="col-md-4">#issueditem.expense_account.getDescription</td>
<td class="col-md-2">#issueditem.quantity.ToString()</td>
<td class="col-md-5">
#*#Html.LabelFor(model => model.item.quantityI, htmlAttributes: new { #class = "col-md-3" })*#
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
</td>
<td class="col-md-1">#issueditem.selecteduomtext </td>
<td class="col-md-1">#issueditem.price.ToString()</td>
</tr>
}
}
Controller
public ActionResult ReceiptPrint(Issue issue)
{
IssueDAO dbdata = new IssueDAO();
dbdata.connectionString = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
getIssue.transactionDate = DateTime.Now; //Sets the transaction date to current date
getIssue.status = -1;
getIssue.docType = "Issue";
ViewBag.StoresReps =dbdata.SelectEmployeesByDept("Stores");
getIssue.employeeDetails.employeeNum = issue.employeeDetails.employeeNum;
getIssue.processedbyDetails.employeeNum = issue.processedbyDetails.employeeNum;
getIssue.inventory_acccount=5520;
Item item = new Item();
try
{
dbdata.createIssue(getIssue, item);//Creates the issue in the database
}
catch (Exception ex)
{
LogWrite logWriter = new LogWrite(ex.ToString());
ViewBag.errorMessage = "Unable to complete the Issue. Please see Log file for more Information";
return View("IssueItem", getIssue);
}
DataSet ds = dbdata.GetReceipt(getIssue.requisitionNumber);
LocalReport localreport = new LocalReport();
localreport.ReportPath = Request.MapPath(Request.ApplicationPath) + #"Reports\Reciept.rdlc";
localreport.DataSources.Add(new ReportDataSource("Receipt_Data", ds.Tables[0]));
localreport.SetParameters(new ReportParameter("Req_num", getIssue.requisitionNumber));
string reporttype = "PDF";
string mimeType;
string encoding;
string fileNameExtension = "pdf";
string deviceInfo = #"<DeviceInfo>
<OutputFormat>PDF</OutputFormat>
<PageWidth>8.5in</PageWidth>
<PageHeight>11in</PageHeight>
<MarginTop>0.25in</MarginTop>
<MarginLeft>0.45in</MarginLeft>
<MarginRight>0.45in</MarginRight>
<MarginBottom>0.25in</MarginBottom></DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localreport.Render(
reporttype, deviceInfo, out mimeType, out encoding, out fileNameExtension,
out streams, out warnings);
var doc = new iTextSharp.text.Document();
var reader = new PdfReader(renderedBytes);
using (FileStream fs = new FileStream(Server.MapPath("~/Receipt" +
Convert.ToString(Session["CurrentUserName"]) + ".pdf"), FileMode.Create))
{
PdfStamper stamper = new PdfStamper(reader, fs);
string Printer = "Xerox Phaser 3635MFP PCL6";
// This is the script for automatically printing the pdf in acrobat viewer
stamper.JavaScript = "var pp = getPrintParams();pp.interactive =pp.constants.interactionLevel.automatic; pp.printerName = " +
Printer + ";print(pp);\r";
stamper.Close();
}
reader.Close();
FileStream fss = new FileStream(Server.MapPath("~/Receipt.pdf"), FileMode.Open);
byte[] bytes = new byte[fss.Length];
fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
fss.Close();
System.IO.File.Delete(Server.MapPath("~/Receipt.pdf"));
return File(bytes, "application/pdf", "receipt.pdf");
}
I can't see anywhere in your controller that you have updated or selected from the model the quantity. I See pulling data from the database, I see where your pushing to the database, but I don't see anywhere your setting the quantity.
Normally you'll have your view (with a begin form)
#using (Html.BeginForm("ActionMethodName","ControllerName"))
{
#Html.TextBoxFor(model => model.item.quantityI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantityI, "", new { #class = "text-danger" })
<input class="button" id="submit" type="submit" value="Submit" />
}
Then in your controller you'd have something to read the model data your passing back. There are three main ways to do this,
1) Using a public FormCollection
ActionResult ActionMethodName(FormCollection collection)
{
string quantity = collection.Get("quantityI);
}
2) Using direct named values
ActionResult ActionMethodNAme(string quantityI)
{
// The quantityI is already stored in the string parameter
}
3) Using a model view
ActionResult ActionMethodNAme(MyClass myItem)
{
// MyClass would be defined as a class containing all your variables pulled from the form so you could do. You need to make MyClass in advance!
string quantity = myItem.quantityI;
}
I have got trouble parsing HTML table to PDF. Table is spreading and it's go out of page. How can I it fix?
I'm using HTMLWorker. It's converting HTML to PDF is good, but that table...
Here is my code(it's in method):
StyleSheet ST = new StyleSheet();
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
HTMLWorker worker = new HTMLWorker(doc);
worker.SetStyleSheet(ST);
worker.StartDocument();
worker.Parse((TextReader)File.OpenText(xmlNode.ChildNodes[i].Attributes["path"].Value.ToString()));
worker.EndDocument();
worker.Close();
How can I tell HTMLWorker so it's create table in PDF is ok? Can I give to worker size of table?
Or maybe should I use other "workers" for example XMLWorkerHelper or XMLWorker. When I use XMLWorker or XMLWorkerHelper I can't set to "workers" my font(I need Cyrillic, and just don't understand how add font). And when I use this "workers" I have the same problem with table.
code with XMLWorker:
//working with XMLWorker
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(fileCSS,true);
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new FileStream(fileHTML, FileMode.Open, FileAccess.Read));
code with XMLWorkerHelper:
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
FontFactory.Register(arialuniTff);
using (var msCss = new MemoryStream(Encoding.UTF8.GetBytes(fileCSS)))
{
using (FileStream fsHtml = new FileStream(fileHTML,FileMode.Open,FileAccess.Read))
{
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, fsHtml, msCss, FontFactory.FontImp as IFontProvider);
}
}
What can You advise to me?
Thank you!
Update
I found one article about XMLWorkerHelper with Cyrillic, but my code doesn't work. I can't understand why.
My code:
using (var msCss = new MemoryStream(Encoding.UTF8.GetBytes(fileCSS)))
{
using (FileStream fsHtml = new FileStream(fileHTMLTest,FileMode.Open,FileAccess.Read))
{
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(arial);
FontFactory.FontImp = fontProvider;
doc.Add(new Paragraph("XMLWorkerHelper"));
doc.Add(new Paragraph("XMLWorkerHelper вот это да!"));
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, fsHtml, msCss, Encoding.UTF8, fontProvider);
}
}
My HTML code(test):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"content="text/html;charset=utf-8"></meta>
<title></title>
</head>
<body>
<p>Привет Мир!</p>
<table border="0">
<tr>
<td><h2 align="center">Акционерное общество «OOO "Ландыш"»</h2></td>
</tr>
<tr>
<td>
<p align="center">Тема:</p>
<p align="center">[THEME]</p>
</td>
</tr>
<tr>
<td>
<div align="right">
<p>Выполнил:</p>
<p>[AUTHOR]</p>
</div>
</td>
</tr>
<tr>
<td><p align="center">[CITY] [YEAR]г.</p></td>
</tr>
</table>
<table border="1">
<tr>
<td>Row 1, Column 1; Столбец 1, Строка 1 </td>
<td>Row 1, Column 2; Столбец 1, Строка 2</td>
</tr>
<tr>
<td>Row 2, Column 1; Столбец 2, Строка 1</td>
<td>Row 2, Column 2; Столбец 2, Строка 2</td>
</tr>
</table>
<img src="img.jpg" alt="picture"></img>
</body>
</html>
I try to add my files into DropDownList, all my files with the relevant property already return by the controller:
// GET: /WebMail/
public ActionResult Index()
{
var fileNameList = db.Captures.ToList().Where(x => x.robotFamily == "WebMail");
//return View(db.Captures.ToList().Where(x => x.robotFamily == "WebMail"));
ViewBag.Files = fileNameList;
return View();
}
Index.cshtml
#model IEnumerable<AutomationCapturesMVC.Models.Capture>
#{
//ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th style="font-size: 20px">
#Html.DisplayNameFor(model => model.fileName)
</th>
<th></th>
</tr>
#Html.DropDownList("Id", (IEnumerable<AutomationCapturesMVC.Models.Capture>)ViewBag.Files, new { id = "WebMail", #class = "btn dropdown-toggle" })
#foreach (var item in Model)
{
<tr>
<td style="font-size: 15px">
#Html.DisplayFor(modelItem => item.fileName)
</td>
<td>
#Html.ActionLink("File Details", "Details", new { id = item.id })
</td>
</tr>
}
</table>
this is my page error:
http://s21.postimg.org/983eokpfq/1231231313.jpg
How about the following?
In controller
public ActionResult Index()
{
var fileNames = GetDatabaseFileNames();
var fileNameList = fileNames.Select(d => new SelectListItem { Text = d.FileName, Value = d.FileName.ToString() }).ToList();
ViewBag.Files = fileNameList;
return View();
}
In View
#Html.DropDownList("DatabaseFiles", (IEnumerable<SelectListItem>)ViewBag.Files, new { id = "DatabaseFiles", #class = "btn dropdown-toggle" })