Dynamicly creating imageButton that calls a JavaScript function in c# - 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.

Related

CMSEditableRegion inside a code loop

I am trying to add a cmseditableregion to my Kentico webpart that exists inside of tabbed content, now the amount of tabs are flexible so I would like to generate this dynamically. I have tried the method that follows (stringbuilder) but it just renders it as html and not as a control when passed to a literal.
for (int i = 1; i <= TabCount; i++)
{
sb.AppendLine("<li class=\"htab-list__item--fininfo active\">");
sb.AppendLine("<a href=\"#financial-result\" class=\"htab-list__link tab-link\">");
sb.AppendLine("<cms:CMSEditableRegion runat=\"server\" id=\"ttl" + i.ToString() + "\" RegionType=\"Textbox\" RegionTitle=\"" + i.ToString() + " Title\" />");
sb.AppendLine("</li>");
Is there a way to make the CMSEditableRegion be able to be set dynamically in the code so that when the loop builds the page code it will be in the right spot as a control and not just html.
The full code has more html and 3 editable regions per loop but it wont even work with just one.
Adding control dynamically is done as follows:
// Let's assume that 'plc' is a placeholder. But it can be any control.
plc.Controls.Add(new LiteralControl("<li class=\"htab-list__item--fininfo active\">"));
plc.Controls.Add(new LiteralControl("<a href=\"#financial-result\" class=\"htab-list__link tab-link\">"));
plc.Controls.Add(new CMSEditableRegion { ID = "someid", RegionType = CMSEditableRegionTypeEnum.TextBox, RegionTitle = "sometitle" });
plc.Controls.Add(new LiteralControl("</li>"));
Also check out MSDN.
I suggest you to create an ad hoc PageType (called DocumentType in Kentico 7) where you can put the HTML text needed. Then you can display it using a Repeater web part or a ASP.NET repeater if, like me, you prefer to work in code.

MenuItem call javascript function

Dynamically building menu items and need to call a javascript function from one of them.
function popWin(url) {
var winHandle = window.open(url, '_blank', 'width=1000,height=700,resizable=yes,top=5,left=5,scrollbars=yes,status=yes');
}
<asp:Menu ID="Menu1" runat="server" StaticDisplayLevels="8" RenderingMode="List" OnMenuItemClick="Menu1_MenuItemClick" CssClass="menu" Width="150px">
</asp:Menu>
The code behind:
string url = "/somepage.aspx";
MenuItem child = new MenuItem();
child.Text = "Some Text";
child.NavigateUrl = "javascript:popWin('" + url + "');";
//child.NavigateUrl = "javascript:window.open('somepage.aspx');";
Menu1.Items[1].ChildItems.Add(child);
Just having some trouble calling the javascript function.
The window.open will work but an extra page opens and I need more control over the window opening.
The reason this needs to be done this way is there's an iFrame on the page that's loading different pages. The RegisterStartupScript was being used in the Menu1_MenuItemClick event but it was refreshing the source of the iFrame.
Thanks for any suggestions.
UPDATE
Trying to go another route on this but just not working right:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin(" + win + ");";
string text = "<span style='cursor:pointer;' onclick='" + script + "'>Some Text</span>";
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);
After coming back to this problem and testing a span tag in html with an onclick event, the problem was simply a bit of syntax:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin('" + win + "');";
string text = "<span style=\"cursor:pointer;\" onclick=\"" + script + "\">Some Text</span>";
//Below is how it should render
//<span style="cursor:pointer;" onclick="popWin('/SomePage.aspx');">Some Text</span>
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);
Thought I would post this just in case anyone else runs into the same issue.

Call javascript from code behind c# sharepoint 2010

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;

How to get the id of a dynamically created html button on its click in jquery

I have several(inside loop) dynamically created html buttons like :
sb.Append("<input type=\"button\" name=\"deleteimage" + id
+ " \" id=\"btndelete" + id
+ "\" value=\"Delete\" class=\"t-button t-grid-delete\" "
+ " style=\"margin-left:10px;\" />");
and I want to get the id of the button on which I click using jquery
Help Me
Thanks
delegate using .on()(jQuery 1.7+) or .delegate()(jQuery 1.6 and lower)
$('body').on('click','input[type=button]',function(){
alert(this.id); // <-- this refers to current clicked input button
});
or
$('body').delegate('input[type=button]','click',function(){
alert(this.id);
});
Or whatever your sb element is replace body with that since it exists on dom load
How about
$('input:button').click(function(){
alert('Clicked ' + this.id);
Try this
$("input[type=button]").click(function()
{
alert(this.id);
});
You can try the following:
$(document).click(function(event) {
var target = event.target;
if ($(target).hasClass("t-grid-delete")) { // check if element has class t-grid-delete is your button
var targetId = $(target).attr("id");
// set your image id with attribute like image_id
// it take easy to get image id $(target).attr("image_id")
}
});
Use 'live' event for dynamically generated html element's event
$("input[type=button]").live('click',function()
{
alert(this.id);
});

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