Call javascript from code behind c# sharepoint 2010 - c#

I have this code in my .ascx.cs file which calls to new page on href.
lblVideoAssessment.Text = "<a href='../SitePages/Assessment.aspx?cat=" + cat + "' height='300px' width='300px' Target='_blank' cssClass='IconDisplayCss'><img src='~/_layouts/images/Assessment.png' border='none'/></a><br/>" + cat;
I want to replace this code to javascript popup page to change look and feel.i want to make page as popup for which i have written a javascript method in .ascx file which is given below:
<script type="text/javascript">
function OpenDialog(URL) {
var NewPopUp = SP.UI.$create_DialogOptions();
NewPopUp.url = URL;
NewPopUp.width = 700;
NewPopUp.height = 350;
SP.UI.ModalDialog.showModalDialog(NewPopUp);
}
</script>
I have called the javascript in code behind like this and it does not work:
lblVideoAssessment.Text = "<a OnClick='javascript:OpenDialog('../SitePages/Quiz.aspx')' height='300px' width='300px' Target='_blank' cssClass='IconDisplayCss'><img src='~/_layouts/images/Assessment.png' border='none'/></a><br/>" + cat;
Please advice what to do.
The same works fine with sharepoint designer.
Please help how to pass the javascript method on OnClick.

It sounds like you simply want the html that you are assigning to lblVideoAssessment.Text to be placed in the page, exactly as it is. For that, an <asp:Label ... /> is not the right type of control to use.
Instead, you want an <asp:Literal ... />. Then the assignment will be basically the same as what you currently have:
litVideoAssessment.Text = "<a OnClick='javascript:OpenDialog('../SitePages/Quiz.aspx')' height='300px' width='300px' Target='_blank' cssClass='IconDisplayCss'><img src='~/_layouts/images/Assessment.png' border='none'/></a><br/>" + cat;

Related

OnClick Event not invoking on IMG Tag

I have a label whose id is lblppb and have assigned an IMG tag as a string as below:
lblppb.Text = "<a href='//media.mercola.com/themes/mercola/images/view-all-health-topics.jpg' target='_blank' id='BannerLink1'><img alt='Banner' src='../Desert.jpg' height='250' width='300'onclick='alert('Hello..!!')'></a>";
This label is in div and it is showing the specified image from src, but when i click on that image i want to generate an alert...
HELP..!
THanks in advance..
They seems to be no space between the image width and the onlick event call
width='300'onclick='alert('Hello..!!')'. You have to space them as per below and then try it again.
width='300' onclick='alert('Hello..!!')'
Alternatively, since your are curious in displaying pop alert message. the the code below should get you going
<html><head>
<script type="text/javascript">
<!--
function validate()
{
alert( "Please provide your Profile Picture!" );
return( true );
}
</script>
</head><body>
lblppb.Text = "<a href='//media.mercola.com/themes/mercola/images/view-all-health-topics.jpg' target='_blank' id='BannerLink1'>
<img alt='Banner' src='../Desert.jpg' height='250' width='300' onclick="return(validate());"></a>";
</body></html>
Give me a shout if you still need further help. Sectona...
First of all I always prefer to use external script rather using static inline scripts. Inline scripts are less maintainable and in case of testing it becomes worst. But when you switch to external script it gives you the reliability to have your code in a separate module that is much more testable.
If you have option to modify your img tag I would surely tell you to do as follows :
Add id attribute in your img and keep everything same. I have named it(id) bannerImg
lblppb.Text = "<a href='http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg' target='_blank' id='BannerLink1'><img alt='Banner' id='bannerImg' src='https://lh5.googleusercontent.com/-WsZ4Q7Y156A/AAAAAAAAAAI/AAAAAAAAABM/vN1-gy0xZQU/photo.jpg' height='250' width='300'></a>";
Now add the following script in your page's head section or any external .js file,
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
$("#bannerImg").click(function () {
alert("Hello..!!");
});
});
</script>
Note : Remember you must include jQuery before using the script.
Or,
when onclick event is fired, call a function and get your stuff done.
<script type="text/javascript">
function alertMe() {
alert("Hello....!!!!");
}
</script>
lblppb.Text = "<a href='http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg' target='_blank' id='BannerLink1'><img alt='Banner' id='bannerImg' src='https://lh5.googleusercontent.com/-WsZ4Q7Y156A/AAAAAAAAAAI/AAAAAAAAABM/vN1-gy0xZQU/photo.jpg' height='250' width='800' onclick='alertMe();'></a>";

Convert panel HTML to PDF using C# ASP.NET

I have a basic form with mostly textboxes and a few checkboxes and radio buttons. Pretty much when a user fills it out and hits submit, I need it to convert and display a PDF with the same structure and offer a print option. I have searched online and I have tried most of the options but nothing works.
I don't expect this to be too difficult, but I am fairly new to C# and can't figure out how to make an HTML panel into a PDF and print it. Any help would be appreciated, thanks in advance!
Here is the HTML for one of the labels and textboxes and the submit button:
<div>
<asp:Label ID="lblDate" runat="server" Text="Date:"></asp:Label>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</div>
<asp:Button ID="SubmitButton" runat="server" Text="Button" OnClick="btnSubmit"/>
Once clicked, the .cs page will go through this:
litDate.Text = "Date: " + txtDate.Text + "<br />";
and update the panel to display the value:
<asp:Panel ID="PDFPanel" runat="server" Visible="false">
<asp:Literal ID="litDate" runat="server"></asp:Literal>
</asp:Panel>
I am not sure if the panel is needed, but this is how I was able to be sure I was getting the value back. Is there a way to go straight from submit to PDF and print?
Use something like http://code.google.com/p/wkhtmltopdf/
This roughly outlines how to do it: https://stackoverflow.com/a/18767473/181771
I made an asp.net website demo taking the contents of a panel or div and generating a pdf from the html. This is using NReco.PdfGenerator (another wkhtmltopdf wrapper):
https://github.com/jay8anks/Asp.net-HtmlToPdf_NReco.PdfGenerator
Yeah, it's a webform, but anyone sharp enough to do mvc should be able to adapt it fairly easily.
Basically, it is using javascript to get the html between a panel (div) tag and store it in a hiddenfield. Pretty straight forward, except if you want to have css or images, you can't use a relative url for them. I actually just embedded the css inline as a string, but there are other ways of doing it.
Then in the codebehind, this gets the html and generates a pdf from it:
protected void SaveHtmlToPdf()
{
string htmlOutput = Server.UrlDecode(HiddenField1.Value);
htmlOutput = string.Join(" ", System.Text.RegularExpressions.Regex.Split(htmlOutput, #"(?:\r\n|\n|\r|\t)"));
htmlOutput = htmlOutput.Replace("\"", "'");
string headerStyle = HeaderStyle();
string finalHtml = headerStyle + htmlOutput;
var strWr = new StringWriter();
var htmlWr = new HtmlTextWriter(strWr);
// base.Render(htmlWr);
var htmlToPdf = new HtmlToPdfConverter();
string filename = (orderId + ".pdf");
string filepath = "~/sales_pdfs";
string combinedFilePath = Path.Combine(Server.MapPath(filepath), filename).ToString();
for (int i = 1; i <= NumberOfRetries; ++i)
{
try
{
htmlToPdf.GeneratePdf(finalHtml, null, combinedFilePath);
break; // When done we can break loop
}
catch (IOException e)
{
// You may check error code to filter some exceptions, not every error
// can be recovered.
if (i <= NumberOfRetries)
{
Thread.Sleep(DelayOnRetry);
}
ltMsg.Text = "There was a problem creating the PDF";
}
}
}
This puts a pdf in a directory so it can be downloaded, but there are other ways that could be handled, as well. We actually wanted a copy of the PDF that someone was generating, so this was the direction we went in.

How to simulate Web page button click in code

I'm trying to simulate a button click in my program in order to get the response from the server. The problem is that the web page "onclick" activate a script in that page
The html look like this:
<script language=javascript>
function frmsubmit(id)
{
document.all("HistoryData1_hiddenID").value=id;
document.all("Form1").submit();
}
</script>
<input type="button" id="btnGo" value="Go" Class="RegularButton" onclick="frmsubmit('0')" >
I used this code that i have seen:
WebBrowser wb = new WebBrowser();
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.GetElementById("btnGo").InvokeMember("click");
Nothing happens. In the real web page I get an html with data that I need. Any ideas?
you can use jquery like
$("#btnGo").click();
in your .cs you will use it like
StringBuilder sb = new StringBuilder();
sb.AppendLine("$(document).ready(function() {");
sb.AppendLine("$('#btnGo').click();");
sb.AppendLine(" });");
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", sb.ToString(), true);
thats it, of course you have to add jquery libraries to html page
Try calling doPostBack
__doPostBack("btnGo', '<event argument here>');
http://wiki.asp.net/page.aspx/1082/dopostback-function/
Use jQuery trigger() function (or triggerHandler, dependingo on your purpose).
I.e.
$('#<%=btnGo.ClientID%>').trigger('click');

Dynamicly creating imageButton that calls a JavaScript function in c#

I have the following c# code that creates image buttons which should call the javaScript method below
var imageButton = new ImageButton();
imageButton.ImageUrl = "Styles/unClicked.png";
imageButton.ID = "btn" + questionName;
imageButton.OnClientClick = "buttonPressed('" + questionName + "')";
Its outputting & # 3 9; instead of the ' in the html code and there for is causing an error (Ive had to add spaces tp prevent SO changing it to a comma)
onclick="buttonPressed('question0')
how to I prevent this?
Please try this one HtmlString (not working).
imageButton.OnClientClick = new HtmlString("buttonPressed('" + questionName + "')");
If it will not work, than you will need to create custom control or use javascript (JQuery) to add handler for click event.
<script>
$("<%=imageButton.ID%>").click(function() {
buttonPressed('<%=questionName%>');
})
</script>
The OnClientClick attribute is very limiting. Not totally sure this will work, but I have use similar code before to handle ghost text in textboxes...
imageButton.Attributes.Add("onclick", "buttonPressed('" + val + "')");
The attribute should not be HTML encoded.

How can i call java script function(in .cs) in the OnClientClick of the link button?

I write script like this in my .cs file :
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\"> function submitform(){");
script.Append(" document.forms['" + ((HtmlGenericControl)frm).Attributes["id"] + "'].submit();} </");
script.Append("script>");
How can i call this function in the OnClientClick of my link button ?
LinkButton hl_process = new LinkButton();
hl_process.OnClientClick = ""
Edit1:
protected Control CreateCommForm()
{
HtmlGenericControl frm = new HtmlGenericControl("form");
frm.Attributes.Add("id", "sal");
frm.Attributes.Add("method", "post");
frm.Attributes.Add("action", "https://------");
/////////////////////////////////////////
HtmlGenericControl hdn_sal_a = new HtmlGenericControl("input");
hdn_sal_a.Attributes.Add("id", "hdn_sal_a");
hdn_sal_a.Attributes.Add("name", "hdn_sal_a");
hdn_sal_a.Attributes.Add("type", "hidden");
hdn_sal_a.Attributes.Add("value", Session["emp_num"].ToString());
/////////////////////////////////////////
HtmlGenericControl hdn_sal_b = new HtmlGenericControl("input");
hdn_sal_b.Attributes.Add("id", "hdn_sal_b");
hdn_sal_b.Attributes.Add("name", "hdn_sal_b");
hdn_sal_b.Attributes.Add("type", "hidden");
hdn_sal_b.Attributes.Add("value", Session["user_name"].ToString());
frm.Controls.Add(hdn_sal_a);
frm.Controls.Add(hdn_sal_b);
column1.Controls.Add(frm);
return frm;
}
separate the concerns The Visual part your application shouldn't be affected if you move your app to java or ruby. that's what separate of concerns is.
write the client script in the client, not in the cs file:
$('#<%= hl_process.ClientID %>').click(function(){
...
$('#formId').submit();
// if the button inside the form:
this.form.submit(); // HTML5
// Or:
$(this).closest('form').submit();
// if the button not inside the form :
var class = $(this).attr('class');
$('form.' + class).submit();
});
Use jquery to bind to the click event instead of doing this on the server side:
Submit Me
then in javascript something like:
<script type="text/javascript">
$('.blah').click(function() {
document.forms[0].submit();
});
</script>
Edit:
While you can generate UI elements with codebehind it's not quite the asp.net way. Use repeaters if you must repeat the generation of controls. Actually, creating multiple forms is not the asp.net way either, as it assumes only one form running at the server context and everything else binds to an event on submission. Anyways, it seems you're still learning asp.net and probably coming form PHP or something similar.
To accommodate your request, I'd advice to stay away from from generating JS on the server side. Give different class names to your forms and use the same method above. You don't need a LinkButton to submit the form, a simple anchor <a> fits the bill.
You can use the ClientID property (if you don't use classes), but you must first attach the parent control to the page for the algorithm to kick in.
So, your code would be something like:
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["onclick"] = "$('#" + frm.ClientID + "').submit();";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
The alternative way (better separation of concerns)
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["class"] = "submitter";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
And in javascript we find the parent form and submit it (this can be in a static js file):
<script type="text/javascript">
$('.submitter').click(function(
$(this).parents('form').submit();
));
</script>

Categories

Resources