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>");
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'm attempting to use RazorEngine 3 to insert HTML elements into a template. When I try this, the resulting string (used later as HTML) ends up displaying the HTML markup rather than utilizing it to render the page.
Code:
var linkText = new HtmlString("" + linkName + "");
string result = Razor.Parse(template, new {MyLink = linkText});
Template file:
Link to file: #Model.MyLink
Resulting HTML:
Link to file: <a href=http://blah.com>Blah link</a>
This functionality was working fine with RazorEngine 2, but I had to upgrade due to another glitch. Additionally, this is a console application so adding #Raw functionality might be complicated.
The answer ended up being to use a string type variable that is passed into the template. The template, in turn uses the Raw() method as seen below.
Code:
string linkText = "" + linkName + "";
string result = Razor.Parse(template, new {MyLink = linkText});
Template File:
Link to file: #Raw(#Model.MyLink)
I set the value of a image control via the following jquery code:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
$('#<%= detailedImage.ClientID %>').
attr('src', imgName + '-large.jpg').
attr('alt', imgAlt);
The picture shows up perfectly in the browser. However I cannot access it's src attribute:
string imgName = detailedImage.Src;
imgName is always an empty string. Any suggestions?
Changing the src of an img, even though the img is placed within a <form> doesn't submit the src to the server. You need to set the new src in something that will be submitted in the form, i.e. a hidden field. Try this:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
var src = imgName + '-large.jpg';
$('#<%= detailedImage.ClientID %>').
attr('src', src).
attr('alt', imgAlt);
$('#<%= hiddenInput.ClientID %>').val(src);
});
If you now have something like this in your markup:
<input type="hidden" id="ImageSource" runat="server" />
You should be able to retrieve ImageSource.Value server-side.
I'm sure there are a number of ways to solve this, depending a lot on factors elsewhere in your page and your application which would contribute to the overall functionality and user experience. But in terms of suggestions, how about this:
Instead of trying to maintain the state of the selected image in the image control, separate it out into a different control. Use a standard img HTML element for displaying the image(s) to the user on the client-side and keep that as solely a user experience concern. Don't use it as part of a form.
Then create a separate control (a hidden field, a text box which has been styled to not be displayed, etc.) and set the path of the image file as the value of that control in your JavaScript. Something like this:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
$('#showImage').attr('src', imgName + '-large.jpg').attr('alt', imgAlt);
$('#<%= imagePath.ClientID %>').val(imgName + '-large.jpg');
});
Note that the src and alt are being set on a standard img tag (with id showImage in this case) and the value that the server-side code cares about is being set on another control entirely (with server-side id imagePath in this case).
I don't have a way of testing this on hand right now, but it's a suggestion. It's possible it may not work, and if that's the case let me know so I can modify/remove this answer. But it seems like it would make sense given that things like TextBox ASP.NET controls are meant to have their values modified on the client-side. (Indeed, in this case you may have better luck with a TextBox styled to not be displayed than with a hidden field.)
I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
<h2><p>Notify:</p> alert</h2>
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you
If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
why don't you give LiteralControl a try?
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
Use a literal control and write your html like this:
literal1.text = "<h2><p>Notify:</p> alert</h2>";
You should really use the Literal ASP.NET control for that.
You can go with the literal control of ASP.net or you can use panels or the purpose.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]
public static string showTxtbox(string name)
{
return showResult(name);
}
public static string showResult(string name)
{
Database databaseObj = new Database();
DataTable dtObj = databaseObj.getMatches(name);
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +
"<tr>" +
"<td><b>Name</b></td>" +
"<td><b>Company Name</b></td>" +
"<td><b>Phone</b></td>"+
"</tr>";
for (int i = 0; i < dtObj.Rows.Count; i++)
{
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+
"</tr>";
}
result += "</table>";
return result;
}
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function.
Result is displayed in the form of table.
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.