I have variable URL strings that are read from an external JSON block into the C# code behind.
I am then creating clickable buttons in a table which need to open a new window and launch those URLs. These are held in object's String variables.
However, I cannot find a way to make a function on the aspx side that opens a window on click and uses the URL string.
Currently I am adding a attribute to the button
Button b = new Button();
b.Attributes.Add("onClick", "OpenURL()");
bCell.Controls.Add(b);
With this I can open a window, but I can't seem to get the URL I deserialized from the JSON string over to the OpenURL()
function OpenURL(url) {var x = window.open(url, 'mynewwin');
function on the front end.
Since the url varies, I cannot hard code it anywhere.
All of the buttons, rows, and cells are generated dynamically from the JSON strings. So no hard coding can happen on these.
//First time poster. Tried to look for solutions but failed
If you know what the url is at the time you're creating the button, you can do:
Button b = new Button();
var url = "some url";
b.Attributes.Add("onClick", string.Format("OpenURL({0})",url));
bCell.Controls.Add(b);
If you don't know the url until after the page is loaded, you can store it in a variable on the page and retrieve it when you click the link.
<script>
var url;
//have whatever you use to set the url call this function
function setUrl(inputUrl){
url = inputUrl;
}
function OpenURL(){
var x = window.open(url,'some window');
}
</script>
Related
I'm looking for a method that replicates a Web Browsers Save Page As function (Save as Type = Text Files) in C#.
Dilemma: I've attempted to use WebClient and HttpWebRequest to download all Text from a Web Page. Both methods only return the HTML of the web page which does not include dynamic content.
Sample code:
string url = #"https://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=" + package.Item2 + "&LOCALE=en";
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
string content = client.DownloadString(url);
}
}
The above example returns the HTML without the tracking events from the page.
When I display the page in Firefox, right click on the page and select Save Page As and save as Text File all of the raw text is saved in the file. I would like to mimic this feature.
If you are scraping a web page that shows dynamic content then you basically have 2 options:
Use something to render the page first. The simplest in C# would be to have a WebBrowser control, and listen for the DocumentCompleted event. Note that there is some nuance to this when it fires for multiple documents on one page
Figure out what service the page is calling to get the extra data, and see if you can access that directly. It may well be the case that the Canadapost website is accessing an API that you can also call directly.
I got a large PDF which is embedded in a homepage and should have interactive links with custom javascript commands in it.
This document should be maintained by some students and it is not possible for them to go through all sites and set the javascript commands after a change in the original word file. So i want them to set hyperlinks in word where an action should occur.
After that i want to remove the hyperlink with iTextSharp and set a javascript action instead.
I can communicate with HTML, find the hyperlinks correctly and can change their url like in this post
Also tried to add this to the annotation action:
string destination = AnnotationAction.GetAsString(PdfName.URI).ToString();
AnnotationAction.Put(PdfName.JAVASCRIPT, new PdfString("this.hostContainer.postMessage(\"" + destination + "\");"));
But it is always calling the original hyperlink before it is executing the javascript. So how can i remove the hyperlink without losing the formation of the text within the document?
You just need to change the value of /S to /JAVASCRIPT and set your JavaScript command as the value of /JS. Instead of changing things, however, I'm just going to blow away the original action and create a new one, just to make sure there isn't any baggage.
The first three line below are from my original answer that you linked to, after that I've killed off the URL changing code and substituted it with the JavaScript code. Since you understood my other post this should make sense hopefully, too.
//Make sure this annotation has an ACTION
if (AnnotationDictionary.Get(PdfName.A) == null)
continue;
//Remove our old action entry just so nothing weird hangs around
AnnotationDictionary.Remove(PdfName.A);
//Create a new action entry
var a = new PdfDictionary(PdfName.A);
//Set it as an action
a.Put(PdfName.TYPE, PdfName.ACTION);
//Set it as JavaScript
a.Put(PdfName.S, PdfName.JAVASCRIPT);
//Set the JavaScript
a.Put(PdfName.JS, new PdfString(#"app.alert('Hello World');"));
//Add it back to the annotation
AnnotationDictionary.Put(PdfName.A, a);
My scenerio is a user could click on 12 different items on the page and depending on which item they click, a div will be populated with text. I was thinking a good way to do this is just pass all the different text strings to the client on their first request rather than doing a possible of 12 different AJAX calls. I figured front loading the client with the initial load time would be better since the text strings aren't long anyways.
What I am trying to figure out is the best way to write a javascript dictionary/hastable in my C# code behind and pass it to the page on load. What would be the best way to do this?
You can create 12 hidden divs, populate them with HTML and show the appropriate one depending on what the user clicked.
You can convert the Dictionary object to a JavaScript object literal, something like:
var pageContent = {
button1: "some content",
button2: "some other content"
// ...
};
Have a look at System.Runtime.Serialization.Json Namespace and this answer for code. You can then populate a div with the content depending on button clicked.
protected void btnHey_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>alert('HEY');</script>");
// if the script is not already registered
if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup"))
ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString());
}
You can take a look at this http://www.dreamincode.net/forums/topic/185586-aspnet-calling-javascript-from-code-behind/ I hope it helps...
From the point of view of the client you've basically got two choices:
Trigger an AJAX call on page load to get the data asynchronously. (See Sjoerd's answer)
Get ASP to push the data directly into your HTML / JavaScript. (See Ewerton / Scorpio's answers)
If you're uncomfortable having ASP generate your JS dynamically you could also get it to output a script tag with your data in it:
<script type="text/json" id="strings">
<asp:Literal runat="server" ID="JavascriptData" />
</script>
Produces:
<script type="text/json" id="strings">
{ "div1" : "First String",
"div2" : "Second String",
"etc" : "And so on" }
</script>
And then read the data in your javascript:
var json = document.getElementById('strings').InnerHTML;
var strings = JSON.Parse(json);
ScriptManager.RegisterStartupScript will do the trick
To solve such a problem myself, I have made a HttpHandler that returns JSON:
public class JsonData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(GetData());
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
}
In the Javascript of my ASPX I use jQuery to retrieve the data:
$.getJSON("/JsonData.ashx", null, function (data) { ... });
This is really an out-of-band solution, in that the ASPX file retrieves a second file with the data.
What I also sometimes see is something like this:
<script>
var myData = '<asp:Literal runat="server" ID="JavascriptData" />';
</script>
Where JavascriptData is then filled in the codebehind. I don't really like this method, but it is simple and it works. Don't forget to escape your quotes.
You can store your html content in a string format in hidden fields, or you can populate 12 separate divs from your server side code. Then write some javascript to show-hide divs based on the button clicks.
Here is the context:
I am building a .aspx page that allows the user to administrate some xml documents we have on our server. The page content is loaded using AJAX, so buttons and forms are dynamically added to the document.
If I had static buttons that I was creating within the .aspx page before it loads on the client's machine, I could attach an event to it very easily. However, I'm dynamically adding and removing buttons and forms on the fly, using jQuery.
Here is a simplified example:
In the following jsFiddle, I'm pretending that the html document contains the following script:
<script language="C#" type="text/C#" runat="server">
void SaveAllChanges(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "foobar";
}
</script>
And that I have a javascript file that contains the following:
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
Obviously the buttons I am creating can not run the function SaveAllChanges with the way it is now. I added the onclick attribute to show what I needed to happen, in a pseudo-code kind of style.
How can I make it so that dynamically added buttons can run the C# method I have defined within the script tag at the top of the document?
Here is the jsfiddle: http://jsfiddle.net/2XwRJ/
Thanks.
You can give all buttons that must save changes a common class (e.g. class="ajaxButton") and have one jQuery method that responds to click events on elements matching that class (use live so that updates to the DOM are reflected).
$("button.ajaxButton").live("click", function(){
// Perform your Ajax callback to run server-side code
});
What you need to do is use something like ..
$(document).ready(function() {
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button id="#dynamicCommentButton" onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
$(document).on('click', '#dynamicCommentButton', function() {
alert($(this).attr('id'));
});
});
You are not going to be able to add the buttons like you have it there as this code here is just adding it as an HTML DOM element and the onclick attribute will be the on the client element. As a result clicking the button will try fire a SaveAllChanges javascript function
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
What would be best would be to create that SaveAllChanges function in javascript and then you can handle it from there. Two of the ways I see you being able to do this are:
Have a http endpoint setup (script service, web api or just posting to a page) that you call using Ajax from your javascript. You can then pass through any needed arguments.
You could have a hidden element and hidden button on the page so that when the javascript is called it populates any arguments you need and then clicks the hidden button and posts the page back.
Personally I would choose the first approach from a user experience stand point as the page will not be posting back each time. I have used something similar to the second approach and it works fine but just feels very clunky.
I'm using the asp.net MVC pattern of having a url like controller/action/id. This works fine if I navigate to the url directly.
I want to have a page where the user can input the id and click a button (or link) which takes them to the correct url.
Do I need to somehow make an action link that points to a varying url based on the input using some client-side script?
Or can I render a Form that GETs the correct url?
Is what I'm doing unusual; should I be doing something else? (Note that the number of ids is too long to list).
Assuming you have the default route set up, you can do the following client-side script (make sure it's in the same file though):
var yourLink = '#Url.Action("controller", "action")';
//should output controller/action/
Then assuming your button has the id myButton and the textbox has the id myTextBox, you can do this jQuery:
$("#myButton").click(function () {
location.href = yourLink + $("#myTextBox").val();
//should output controller/action/5 for example, although you might
//want to make sure they've put a "correct" value in here
});