I am trying to generate a URL that contains a UNC path as one of the query string variables. The URL will open in a pop up window when an ASP.NET button control is clicked by the user. When the clicks the button, the backwards slashes are removed from the UNC path causing the page to break.
The button renders correctly in the page source file with all the backward slashes.
Is there any way to prevent this?
Here is my source code:
Code behind:
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + url + #"')");
ASPX page
<script language="javascript" type="text\javascript">
function FullPop(Newurl) {
Win = window.open( Newurl,"Monitor", "fullscreen=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600,top=50,left=50");
Win.focus();
}
</script>
<asp:button id="MyButton" runat="server" cssclass="mycss" text="View Actual Target" />
Update
Server.UrlEncode does not work. Same behavior.
Update 1
Based on Daniel Lew's answer, I developed the following solution:
protected void Page_Load(object sender, EventArgs e)
{
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + this.EscapeforJavaScript(url) + #"')");
}
private string EscapeforJavaScript(string url)
{
return url.Replace(#"\", #"\\");
}
You have to URL encode the value that you put in the URL:
string url = "http://www.mysite.com/page.aspx?a=" + Server.UrlEncode(unc);
Edit:
To safely put the url in the Javascript code, you also have to encode the string for being a literal string:
MyButton.Attributes.Add("onclick", #"FullPop('" + url.Replace(#"\", #"\\").Replace("'", #"\'") + #"')");
(The javascript: protocol is only used when the Javascript is used as href for a link, not when you put code in an event like onclick.)
I don't know anything about asp.net, but I have had experience with problems when adding text straight into JavaScript before through templating. Have you tried escaping the backslashes on your url, to avoid this?
// Returns "\myservermyfoldermyfile.txt", due to escpaing the backslash.
alert("\\myserver\myfolder\myfile.txt");
// Returns correct value of "\\myserver\myfolder\myfile.txt"
alert("\\\\myserver\\myfolder\\myfile.txt");
You may want to try URLEncoding your string on your server side, using the following method:
public static string UrlFullEncode(string strUrl)
{
if (strUrl == null)
return "";
strUrl = System.Web.HttpUtility.UrlEncode(strUrl);
}
I'm not 100% sure it if will replace the backslashes, but it's worth a try.
Related
In start page: I want to pass a directory path to a popup window page when client click on LinkButton lbtnEditText
<asp:LinkButton ID="lbtnEditText" runat="server" Text="Edit Text" CommandArgument='<%# Eval("Path") + "," + Eval("Name")%>' OnCommand="Button1_Click"></asp:LinkButton>
And the code behind:
protected void Button1_Click(object sender, CommandEventArgs e)
{
string[] values = e.CommandArgument.ToString().Split(',');
string queryString =
"editpage.aspx?path="
+ values[0];
string newWin =
"window.open('" + queryString + "');";
ClientScript.RegisterStartupScript
(this.GetType(), "pop", newWin, true);
}
The queryString exactly is = "editpage.aspx?path=D:\\C#Projects\\website\\Lecturer\\giangvien\\profile.xml" (I check it when I debug)
But In destination page (popup window): editpage.aspx
string path = Request.QueryString["path"];
string content = File.ReadAllText(path);
if(content!=null)
textarea.Value = content;
It has an error: Could not find file 'D:\C#Projects\website\C
Try to debug, the path I recieved is just only : "D:C"
And in the address bar of editpage.aspx display:
http://localhost:41148/website/editpage.aspx?path=D:C#ProjectswebsiteLecturergiangvienprofile.xml
Help!!! Why is the path changed when I pass it to the editpage???
The reason behind happening so is :: you are passing query string data which is having unexpected characters which are '\,#'.
The solution to this is escape and encode this values before setting as query string values
Encoding Urls correctly is unfortunately required skill for anyone doing web development...
Everything after # is "hash" portion of Url and browser don't need to send it to server. More formal name is fragment identifier.
What you need to do is encode value of path query parameter correctly (i.e. with encodeURIComponent funcition in JavaScript).
To give you the actual solution for C#:
string queryString = "editpage.aspx?path=" + System.Web.HttpUtility.UrlEncode(values[0]);
see reference for encoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
and decoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode%28v=vs.110%29.aspx
i have some html content and i stored it in string variable and i want to print it directly.Is there any way in c# ?i have a javascript code which is not working
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<SCRIPT LANGUAGE=\"JavaScript\">function printsheet(" + emailbody + "){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</Script>");
You have many ways to do that.
One way, make the string public
public string emailbody="HTML i need to send";
and on aspx page you render it as:
<%=emailbody%>
One other way is to use a Literal control and render it there. When you have UpdatePanel this is the only way.
Eg, you place the Literal on page, on the point you wish to render your text as:
<asp:Literal runat="server" id="txtRenderOnMe" />
and on code behind you type:
txtRenderOnMe.Text = "HTML i need to send";
Now, in your case the issue is that you render a string on the javascript code without the quotas as the other jesse point out on their comments.
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<script language=\"JavaScript\">function printsheet('" + emailbody + "'){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</script>");
So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?"+url);
where url holds something like "model=2k01&type=black&category=variable".
Unfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.
UPDATE:
Here is the part in my html code that is generating the url stuff:
<a class='modelsBlue' href = '#' data-link='model=" + $(this).find('model').text() + "&type=" + category + "'>" + $(this).find("model").text() + "</a>
and #image preview is in my code as:
<div id = "imagePreview"></div>
When I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:
Microsoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly
Here is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:
namespace ModelMonitoring
{
public partial class imageProcess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("test");
foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
Response.Write(f);
Response.Write("<br />");
}
}
}
}
SECOND UPDATE:
I don't get the error running in chrome or firefox, but the files are not being output.
Turns out it was a whitespace issue. I had to add a wrapper around:
$(this).find('model').text()
to read:
$.trim($(this).find('model').text())
becuase the xml file I was reading from had whitespace around the model name. Thanks to anyone who replied!
I have an IFrame embedding a youtube video. I want to create a textbox where user (admins) can paste a new src (URL) of video and the IFrame take the new source. Here is what I have so far:
protected void Edited_Click(object sender, EventArgs e)
{
// HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
string url = TextBox1.Text;
frame1.Attributes["src"] = url;
}
And in the html code is the Iframe:
<div id="video">
<iframe title="YouTube video player" runat="server" width="420"
frameborder="1" style="height: 265px; float: left;
text-align: center;" id="frame1"
name="frame1" align="middle"></iframe>
<br />
</div>
I don't set any src in the beginning but when I paste a URL in the textbox and hit the button, the Iframe doesn't displays anything.
Other responses don't answer the question, they provide an alternative. The question is how to set iFrame src from C#. I'll answer that here.
I'm all for "right tools for the job" and use that mantra a lot myself - but only when the other tools are "wrong". That hasn't been established here. Can someone provide a good technical reason why this should not be done in code-behind?
I think the issue #Pepys is experiencing might be due to something in the URL, which he hasn't provided yet. For example, maybe his URL includes ampersands or other characters which need to be escaped.
The following code works fine for me:
excelframe.Attributes["src"] =
#"https://r.office.microsoft.com/r/rlidExcelEmbed?"
+ #"su=-0000000000"
+ #"&Fi=zzzzzzzzzzzz!111"
+ #"&ak=x%3d9%26x%3d9%26x%3d!zzzzzzzzzz"
+ #"&kip=1"
+ #"&AllowTyping=True"
+ #"&ActiveCell='sheet1'!C3"
+ #"&wdHideGridlines=True"
+ #"&wdHideHeaders=True"
+ #"&wdDownloadButton=True";
You need to do this on the client browser, not server-side. I would suggest something like:
// (Add inside script element in head of page html)
window.onload = function() {
document.getElementById('<id of input>').onchange = function() {
changeFrameUrl();
}
};
function changeFrameUrl() {
var inputVal = document.getElementById('<id of input>').value;
document.getElementById('<id of iframe>').src = inputVal;
}
Hope this helps - it's off the top of my head though, so don't diss me if it doesn't work first time!
I found a good way to check if a file exists and read the contents if it does, but for some reason I can't create a method out of it.
Here's what I have so far:
<script runat="server">
void Page_Load(Object s, EventArgs e) {
lblFunction.Text = mwbInclude("test.txt");
}
string mwbInclude(string fileName) {
string inc = Server.MapPath("/extra/include/" + Request["game"] + "/" + fileName);
string valinc;
if(System.IO.File.Exists(inc))
{
valinc = System.IO.File.ReadAllText(inc);
}
return valinc;
}
</script>
I wish I could provide more info, but the server this is on doesn't show any feedback on errors, just a 404 page.
I think
valinc = Response.Write(System.IO.File.ReadAllText(inc));
should be
valinc = System.IO.File.ReadAllText(inc);
Why are you setting the Text property and calling Response.Write? Do you want to render the text as a label, or as the whole response?
If you're getting a 404, it's because your page isn't being found, not because there's a problem with the script itself. Have you tried ripping out all of the code and just sticking in some HTML tags as a sanity check?