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!
Related
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!
Error: missing } in XML expression
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=FRXTn%2fX1N8Wy8C%2fdJqQmDjrOEECv%2fRwauMVX6ZTipAM%3d
line: 0, column: 188
code:
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
CODE:
public static void ShowAsync(string sMessage, MessageBoxTypes sType, Control control, Page pPage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
string sMsg = sMessage;
sMsg = sMsg.Replace("\n", "\\n");
sMsg = sMsg.Replace("\"", "'");
sb.Append(#"$(document).ready(function() {");
sb.Append(#"Sexy." + sType + #"( """ + sMsg + #""" );");
sb.Append(#"});");
sb.Append(#"</" + "script>");
ScriptManager.RegisterClientScriptBlock(pPage, typeof(Page), control.ClientID, sb.ToString(), true);
}
if i change true to false in RegisterClientScriptBlock then i get
error: $ is not defined
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=dH0ry1kng6MwGCRgCxXg8N5nCncbzPzn3TAOEI0tAY4%3d
line: 0
i call this popup like:
MessageBox.ShowAsync("Can not copy files.", MessageBoxTypes.alert, this, Page);
What can be wrong. If i copy this (JQUERY)
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
into some .aspx page popup works. But if i call it from code behind and daypilot pro in this updatepanel form then i get this error.
Can be problem that two ajax framewroks mixed themself? How to prevent this?
i try with jquery.noConflict but it is the same
$.noConflict();
jQuery(document).ready(function() { Sexy.alert("Can not copy files."); });
Thx
If you change the last parameter in RegisterClientScriptBlock from true to false it will not add the script tag anymore. Currently with the setting to true, you have the script tag twice. Not sure what happens, but can't be good :-)
$ sounds like jquery? You don't mention what you are using? I mix ASP.NET Ajax with jquery and that works fine. What Version are you on?
I have a web application project to support file transfer operations to vendor product backend. It's composed of 2 HTTPHandler files compiled into a website on a Win2003 server with IIS 6.0:
UploadHandler.ashx
DownloadHandler.ashx
These files get "POSTed to" from a ColdFusion website that exposes the user interface. In a way, my job is done because these handlers work and have to be called from ColdFusion.
Yet, I am very frustrated with my inability to get my own "test UI" (default.aspx) to use in my testing/refinement independent of ColdFusion.
<asp:Button ID="DownloadButton" PostBackUrl="~/DownloadHandler.ashx" runat="server" Text="Download"/>
Using a PostBackUrl for Download works nicely - when the DownloadHandler.ashx is entered, it finds its key input value in context.Request.Form["txtRecordNumber"];
But I cannot use this technique for Upload because I have to do some processing (somehow read the bytes from the chosen fileupload1.postedfile into a FORM variable so my UploadHandler.ashx file can obtain its input from Request.Form as with Download).
My first approach tried using HTTPWebRequest which seemed overly complex and I could never get to work. Symptoms began with a HTTP 401 status code and then morphed into a 302 status code so I researched other ideas.
Here is my latest code snippet from my default.aspx:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
BuildFormData();
//Server.Transfer("UploadHandler.ashx", true);
Response.Redirect("~/UploadHandler.ashx");
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=anyname1~udf:OPEAnalyst=anyname2~udf:Grant Number=0102030405";
}
Attempts to use Server.Transfer (above) to my .ashx file result in an error:
error executing child request for UploadHandler.ashx
Attempts to use Response.Redirect (above) to my .ashx file result in GET (not POST) and Trace.axd of course shows nothing in the Form collection so that seems wrong too.
I even tried clone-ing my .ashx file and created UploadPage.aspx (a webform with no HTML elements) and then tried:
Server.Transfer("UploadPage.aspx", true);
//Response.Redirect("~/UploadPage.aspx");
Neither of those allow me to see the form data I need to see in Request.Form within my code that processes the Upload request. I am clearly missing something here...thanks in advance for helping.
EDIT-UPDATE:
I think I can clarify my problem. When the UploadHandler.ashx is posted from ColdFusion, all of the input it needs is available in the FORM collection (e.g. Request.Form["fileData"] etc.)
But when I use this control it generates a postback to my launching web page (i.e. default.aspx). This enables me to refer to the content by means of FileUpload1.PostedFile as in:
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
}
Yet I am not using the FileUpload1.PostedFile.SaveAs method to save the file somewhere on my web server. I need to somehow - forgive the language here - "re-post" this data to an entirely different file - namely, my UploadHandler.ashx handler. All the goofy techniques I've tried above fail to accomplish what I need.
EDIT-UPDATE (20 Aug 2009) - my final SOLUTION using Javascript:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ctlForm.Text = BuildFormData();
String strJS = InjectJS("_xclick");
ctlPostScript.Text = strJS;
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
private String InjectJS(String strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm1 = document.forms.namedItem('{0}');");
strScript.Append("ctlForm1.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
protected string BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
// Convert the binary input into Base64 UUEncoded output.
string base64String;
base64String =
System.Convert.ToBase64String(fileContent,
0,
fileContent.Length);
objBinaryData.Text = base64String;
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=Patterson, Fred~udf:OPEAnalyst=Tiger Woods~udf:Grant Number=0102030405";
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"_xclick\" name=\"_xclick\" target=\"_self\" action=\"http://localhost/HTTPHandleTRIM/UploadHandler.ashx\" method=\"post\">");
strForm.Append("<input type=\"hidden\" name=\"strTrimURL\" value=\"{0}\" />");
strForm.Append("<input type=\"hidden\" name=\"objBinaryData\" value=\"{1}\" />");
strForm.Append("<input type=\"hidden\" name=\"b64fileName\" value=\"{2}\" />");
strForm.Append("<input type=\"hidden\" name=\"strDocument\" value=\"{3}\" />");
strForm.Append("<input type=\"hidden\" name=\"strMetaData\" value=\"{4}\" />");
strForm.Append("</form>");
return String.Format(strForm.ToString()
, txtTrimURL.Text
, objBinaryData.Text
, b64fileName.Text
, txtTrimRecordType.Text
, strMetaData.Text);
}
Sorry if I'm missing something, but can't you simply use a plain HTML form to upload files to your handler:
<form action="UploadHandler.ashx" method="post" enctype="multipart/form-data">
Choose file to upload:
<input name="file" type="file" size="50">
</form>
What worked for me was to inject a new FORM and some Javascript to submit the FORM to the UploadHandler.ashx. This (for me) was easier to grasp than the HTTPWebRequest technique.
John Galt,
The only way to do what you want is using HttpWebRequest.
Here is good example of a Class that do what you want. I've made to send image and form values to picassa serve sometime ago (I know I could use Picassa API, but I did it for fun).
You only need to pay attention to the 'SendPhoto' function to get hints on what you have to do to make HttpWebRequest to do the work.
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?
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.