I am using WrappedJsonResult as a return statement in one of my action methods.
Note:
I couldn't upload a complete code as I am working out this in a project.
My form is something like this:
<form
action="/controller/actionmethod"
enctype="multipart/form-data"
id="excelUploadForm"
method="post"
name="excelUploadForm"
target="FileUploadTarget">
//some contents inside form
</form>
<iframe
id="FileUploadTarget"
name="FileUploadTarget" >
</iframe>
My code is:
return new WrappedJsonResult
{
Data = new
{
isSuccess = true,
CusEvent = "close",
CusMsg = "File Uploaded Successfully"
}
};
On successful upload, the above jsonresult opens in new tab in textarea.
Html generated & opened in new tab to get the WrappedJsonResultis:
<html>
<head></head>
<body>
<textarea id="jsonResult" name="jsonResult">
{
"isSuccess":true,
"CusEvent":"close",
"CusMsg":"File Uploaded Successfully"
}
</textarea>
</body>
</html>
My problem:
Jsonresult opens in new tab. That I want to prevent it.
I cannot simulate where the problem occurs. Whether this occurs due to iframe or WrappedJsonResult or something else.
What is the problem with this ?.
Related
In the master page of all my web form pages I've set up an overlay which blocks user interation whenever form submitted until browser renders next page response:
<script type="text/javascript">
function overlayWhenSubmit() {
document.getElementById('spinnerOverlay').style.display = 'block';
}
//spinnerOverlay has position:fixed and top/bottom/left/right:0
</script>
protected override void OnPreRender(EventArgs e) {
this.ClientScript.RegisterOnSubmitStatement(
typeof(Page), null, "overlayWhenSubmit();"
);
base.OnPreRender(e);
}
This works great until I try to provide file download:
public static void DownloadFile(this System.Web.HttpResponse #this, string physicalFilePath) {
#this.ContentType = "application/octet-stream";
#this.AppendHeader("Content-Disposition", $"Attachment; filename=\"{Path.GetFileName(physicalFilePath)}\"");
#this.TransmitFile(physicalFilePath);
}
// ... then in some event handler in my page:
Response.DownloadFile(thePathOfFileToDownload);
The file downloads OK, but the original page keeps being overlaid and therefore unusable.
Is there a way the page can get notified when the submitted request has finished so it can turn off the overlay?
The closest thing so far is try not to popup the overlay for the control which leads to non-HTML response:
<script type="text/javascript">
function overlayWhenSubmit() {
if (!document.getElementById('noOverlayWhenSubmit').value)
document.getElementById('spinnerOverlay').style.display = 'block';
document.getElementById('noOverlayWhenSubmit').value = '';
}
function noOverlayWhenSubmit() {
document.getElementById('noOverlayWhenSubmit').value = true;
}
</script>
<input type="hidden" id="noOverlayWhenSubmit" value="" />
<asp:Button runat="server" OnClientClick="noOverlayWhenSubmit()"></asp:Button>
I want to create a WebApp, that does the following:
User clicks button on WebApp to run script
Get User eMail
Create new Google Spreadsheet (name=eMail)
get Url of that Spreadsheet
Automatically open Url in new Tab
Step 5 is where I am stuck.
I have used window.open(url) before, however that only seems to work when you run code via a Spreadsheet. What I wanna do is displaying the button on my .html and run everything only with the WebApp but I can't do that because I can not use SpreadsheetApp.getUi() from that context.
Is there another way to do this?
Here is the Error im getting:
EDIT: Seems I had some minor mistakes in my Code.gs I think i fixed that now. Still same issue tho
Thank you guys in advance! :)
Here is some sample code:
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("page");
}
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
var url = createFile(email);
openUrl(url); //THIS ONLY WORKED FROM WITHIN SPREADSHEET
lock.releaseLock();
}
}
function createFile(email){
var newSS= SpreadsheetApp.create(email);
var file = DriveApp.getFileById(newSS.getId());
var url = file.getUrl();
return url
}
function openUrl( url ){ //HAS TO CHANGE
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
}
page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Click Button!</h1>
<button id="btn">Run</button>
<script>
document.getElementById("btn").addEventListener("click",sendRequest);
function sendRequest(){
google.script.run.clickEvent();
}
</script>
</body>
</html>
Get url from app script and open spreadsheet in new tab wit JavaScript
Update app script function
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
lock.releaseLock();
return createFile(email);
}
}
Also update JavaScript Code
function sendRequest(){
google.script.run.withSuccessHandler(
function (link) {
window.open(link, '_blank').focus();
}
).testCSV3();
}
Reference: Communicate with Server Functions
I'm trying to make a website where users can make a pdf. I want to show the pdf directly next to the button when I press "create worksheet". I tried to do it with javascript and php, but I get a weird syntax in my iframe instead of the actual pdf. Does anybody know the correct way of doing this?
<?php
$titel = "TITLE";
require_once('tcpdf/tcpdf.php');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$obj_pdf->SetTitle("educationworksheet.com");
$obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);
$obj_pdf->setPrintHeader(false);
$obj_pdf->setPrintFooter(false);
$obj_pdf->SetAutoPageBreak(TRUE, 10);
$obj_pdf->SetFont('helvetica', '', 12);
$obj_pdf->AddPage();
$content .= '
<h3 align="center">TITLE</h3><br /><br />
<h4 align="left">This is what we are gonne do '.$titel.'</h4><br /><br /><h4 align = "left">Name:____________________________</h4>
';
$obj_pdf->writeHTML($content);
$obj_pdf->Output('sample.pdf', 'I');
?>
<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pdf_viewer").srcdoc = this.responseText;
}
};
xhttp.open("GET", "/test2.php", true);
xhttp.send();
}
</script>
</head>
<body>
<button height="10px" width="30px" onclick="loadDoc()" name="create_pdf" value="create worksheet">create worksheet</button>
<iframe id="pdf_viewer"></iframe>
</body>
</html>
Firstly, the issue is the browser will not interpret the PDF data as a PDF in that way. srcdoc is treated as raw HTML.
There are a couple of different ways to accomplish your "generate on click" functionality:
1) You could just drop the AJAX entirely and just use HTML form markup to accomplish this. Using the target attribute on the form element to target your PDF viewer iframe.
<body>
<!-- Set up our form to target the PDF viewer iframe.-->
<!-- Note: This will work with both GET and POST methods -->
<form action="/test2.php" method="get" target="pdf_viewer">
<input type="text" name="titel">
<button height="10px" width="30px" type="submit" name="create_pdf_btn" value="create worksheet">create worksheet</button>
</form>
<!-- Initially, frame is blank, will update to PDF generation URL on form submit.
I created a special empty HTML file for this purpose. -->
<iframe name="pdf_viewer" id="pdf_viewer" src="blank.html"></iframe>
</body>
and then in test2.php you simply generate your PDF inline as you already are.
2) Generate the file on your server and use the AJAX response to pass where the saved PDF is. This answer below opens a new window with window.open but you can simply replace that window.open line with one that updates document.getElementById('pdf_viewer').src with the new URL.
https://stackoverflow.com/a/46529459/395384
3) Return Base64 and use a lengthy data URL. For an example of that, see here:
https://stackoverflow.com/a/35197585/395384
I'm trying to create web application that consisting an
editable cshtml view page
and then
save that edited content as a PDF once I click the button
So this is the whole cshtml view page ,
#model IEnumerable<int>
#{
ViewBag.Title = "Create Template";
}
<!DOCTYPE html>
<html>
<head>
<title>Create a Template</title>
</head>
<body>
<div id='template'>
<h1 contentEditable='True'>Product Name</h1>
<div >
<h2 contentEditable='True'>Product Description</h2>
<p contentEditable='True'>London is the capital city of England.</p>
</div>
</div>
<button id="btn_sumbit" type="button" class="btn btn-danger submit">Save as PDF</button>
</body>
</html>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$('#btn_sumbit').on('click', function () {
var div_value = document.getElementById('template').innerHTML;
RazorPDF.PdfResult(div_value, "PDF");
});
</script>
}
I'm using RazorPDF to do this task , but once I click this button it doesn't saving to PDF
I can edit this cshtml view page , I want to save that finally edited content as pdf (which is dynamic view)
I think you're doing it wrong. The line "RazorPDF.PdfResult(...)" belongs in the Controller not in the View.
Watch this Video: http://nyveldt.com/blog/post/Introducing-RazorPDF
It should give you a clearer understanding of how things work in RazorPDF.
EDIT:
Just create a Controller method, that generates a PDF-View based on Parameters.
public ActionResult Pdf(string name, string description) {
var product = new Product();
product.Name = name;
product.Description = description;
var pdfResult = new PdfResult(product, "Pdf");
return pdfResult;
}
Of course you need to create a Product-Class that holds the information.
In your Javascript part you can write:
location.href = #Url.Action("Pdf", "Controllername") + "?name=" + name + "&description=" + description;
This will hopefully generate a link that you can follow in Javascript. name and description are Javascript variables that hold the information that was typed by the user.
Do you understand? My approach would be to generate the PDF content in a different view (like in that video) based on the information of your editable view.
Tell me if it worked. ;-)
I have a code that is supposed to show an image and refresh that image every 1 second. I have two .aspx pages, one saves the new image to a file, the other is to display the new image. It is not refreshing with the javascript code. it will display the new image if I hit F5 or refresh the page from the address bar, but not with the code. I cannot debug because I do not have administrative privileges on this computer (at work) so I want to try to add something like "num = num+1" and then display num in a textbox. I want to do this to see if my code is even entering the javascript at all.
Here is the code for the viewer page with the javascript:
<body>
<form id="form1" runat="server">
<div style="height: 60px">
<%--<asp:Image ID="Image1" runat="server" /> --%>
<img src="/video.aspx" id="the_image" alt="" />
<script type="text/javascript" language="javascript">
function refreshImage() {
objIMG = document.getElementById('the_image');
objIMG.src = objIMG.src.substr(0, objIMG.src.indexOf('&nocache=')); +'&nocache=' + Math.random();
}
$(document).ready(function () {
setInterval(refreshImage(), 1000);
})
</script>
<br />
</div>
</form>
</body>
If you are interested here is the code to save the new image to a file:
namespace PlayVideo
{
public partial class Video : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is where I originally had the function that saves the new image.
//string saveTo = #"location to save new image";
//FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.ReadWrite);
using(FileStream fs = File.Open(#"C:Location of file", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
ReadWriteStream(fs, writeStream);
}
Response.Clear();
Response.TransmitFile("~/images/test.jpg");
}
// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}
I don't really no javascrict, I got the code I'm using online. I want to just add that debug line. Can someone help? I'm using Visual Studio 2010, if you're wondering.
console.log(yourData);
and before running it press F12 and go to Console tab. Using Firefox with Firebug plugin would help too.
Depending on the browser you are using to view the page, it probably has a developer toolbar or a set of dev tools built in. You can use this to debug your javascript without needing any elevated privileges.
You can access them in IE but hitting F12.