with json data, created a table with for loop and added dynamic buttons in different conditions, am looking how to add one onclick event for all buttons and get the value of clicked button value or id.
Thank you for your help
dynamic jsondata = JsonConvert.DeserializeObject(responseData);
for (int i = 0; i < jsondata.val.Count; i++)
{
htmlTable.AppendLine("<tr>");
htmlTable.AppendLine("<td>"+jsondata.val[i].id+"</td>");
htmlTable.AppendLine("<td>"+jsondata.val[i].Name+"</td>");
htmlTable.AppendLine("<td>"+jsondata.val[i].desc+"</td>");
string getStatus = GetStatus(url);
if(getStatus=="0")
htmlTable.AppendLine("<td>" + "<input id='ctb"+i+ "' type='button' value='START'></td>");
else if(getStatus=="1")
htmlTable.AppendLine("<td>" +"<input id='ctb"+i+ "' type='button' value='STOP'></td>");
else
htmlTable.AppendLine("<td>" + "<label> Error Occured </label></td>");
htmlTable.AppendLine("</tr>");
}
htmlTable.AppendLine("</table>");
litTable.Text = htmlTable.ToString();
This is a simple demo, But you can do the same in your scenario as well. I just implemented this sample in WebForm. If I am mistaken do comment please.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
divContainer.InnerHtml = "<div id='mysamplecontrol' onclick='thisismyclick(this);'>Start</div>";
}
}
<form id="form1" runat="server">
<div runat="server" id="divContainer"></div>
<script>
function thisismyclick(control) {
alert(control.id);
}
</script>
</form>
Hi it just so happens that I have to need this kind of approach (or any suggestion if you have)
this code produce table
while (rd.Read())
{
resultsHtml.Append("<tr class='odd gradeX'>");
resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
resultsHtml.Append("<td>" + rd["region_tag"].ToString() + "</td>");
resultsHtml.Append("<td class='center'>");
resultsHtml.Append("<div class='tooltip-demo'>");
resultsHtml.Append("<a class='btn btn-info' href='regionEdit.aspx?id=" + rd["region_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
resultsHtml.Append("<asp:Button ID='btnDelete' runat='server' Text='Login' CssClass='btn btn-outline btn-primary' Style='width: 100px;' OnClick='btnDelete_Click' />");
resultsHtml.Append("</div>");
resultsHtml.Append("</td>");
resultsHtml.Append("</tr>");
}
if you will notice there is an asp:button there. because i want that if the user clicks that button, it will just delete it. So I put an
public void btnSubmitDelete_Click(object sender, EventArgs e)
{
}
but the things is. It is not displaying and I can't figure out how to put the region_id in the asp:button to determine which is which to delete and every loop of the while. Please help
i think when u want to add an asp control and show that control to end user u should add dynamically control to a placeholder or panel like this code :
<asp:PlaceHolder runat="server" ID="_plchControles"></asp:PlaceHolder>
and in code bihind :
var btn = new System.Web.UI.WebControls.Button();
btn.Text = "sample";
btn.ID = "btnSubmitDelete";
btn.OnClientClick += btnSubmitDelete_Click;
_plchContent.Controls.Add(btn);
Your script will work as HTML control and you can bind click event from Javascript. To do so define a WebMethod in c# and call it from Javascript click event.
e.g.
$("#btnDelete").on("click",function(e)
{
var para=[]
para.param1=val1;
para.param2=val2;
$.post("/path/delete",para,function(result)
{
});
});
C#
[WebMethod]
public void delete(string param1,string param2)
{
//Delete code here
}
else
mohammadreza izadi answers will work if you want to asp.net control but you have to make object of button as defined not string.
Warning: I am a novice when it comes to ASP and javascript - I'm more used to desktop apps. Web development is completely new to me.
I have inherited an ASP.net project that I need to keep up-to-date.
My current problem is that I need to display the client time in a text control (label or literal control - doesn't have to specifically be one of those, I just need to show it in text) when the user has clicked a button to 'Save'. If I do it server-side, in the 'SaveChanges' function, I get the time of where the server is.
My button is defined as below:
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
And my Literal/Label is:
<asp:Label ID="SaveTime" runat="server"></asp:Label>
I have found a javascript function to calculate the client time from one of the other questions on here: (EDIT: I have updated this function so that the text value of my label is being assigned a value)
<script type="text/javascript">
function GetDate(date) {
CurTime = new Date(date);
var offset = (new Date().getTimezoneOffset() / 60) * (-1);
var utc = CurTime.getTime() + (offset * 60000 * (-1));
var serverDate = new Date(utc + (3600000 * offset));
var dateString = (serverDate.getMonth() + 1) + "/" + serverDate.getDate() + "/" +
serverDate.getFullYear() + " " + serverDate.toLocaleTimeString("en-US", { hour12: true });
document.getElementById('<%=SaveTime.ClientID%>').Text = dateString;
}
</script>
My problem is I don't know where to put this javascript function in my apsx page, or how to set the Text value of my label to the date string calculated in the function. I don't even know for sure how to 'call' this function...
So my questions are:
Where do I have to define the javascript function?
How to I 'call' this javascript function when the user clicks the 'Save' button, so that the text one my age is updated?
You can use Java Script Function like
<script type="text/javascript" language="javascript">
function javascriptFunction()
{
}
</script>
call this function
If you Used Update Panels Then You can Use in .Cs Page:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
or On Button's Click in .aspx page
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
onClientClick="javascriptFunction();"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
Other Wise You can Use in .cs page
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
set value of Label in javascript:
document.getElementById('<%=SaveTime.ClientID%>').value = "Your Date";
for label :
void Page_Load(object sender, EventArgs e)
{
lblMyLabel.Attributes.Add("onclick",
"javascript:alert('ALERT ALERT!!!')");
}
Here's the thing, I now have a working prototype of what I want and it seems to work perfectly for what I want to do. With that said, this cannot POSSIBLY be the best way to do it. And by best I mean both in terms of program simplicity but also HOW i actually coded it. Anyways first a description of what the page should do:
1) the page contains a textbox (Textbox1), a placeholder (Placeholder1), and a button (Button1)
the code for this is simple:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<hr />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<hr />
2) the user can put a number into the textbox (lets say 99) and click the button. the placeholder will then be filled with 99 textboxes with a "save" button next to each one
3)the user can edit any textbox and click save next to it and the function that is then called by the button click event needs to be able to have access to A) the textboxes current value, B) the textboxes old value, C) any amount of meta data
here is my current working solution:
protected void Page_Load(object sender, EventArgs e)
{
createStuff(false);
}
void test(object sender, EventArgs e)
{
Button btn = (Button)sender;
Response.Write(btn.ID + "Clicked" + "<br />");
Response.Write("Metadata: " + Session[btn.ID + "a"] + "<br />");
Response.Write("Old text: " + Session[btn.ID + "b"] + "<br />");
TextBox txtBlah = (TextBox)PlaceHolder1.FindControl("txt"+btn.ID);
Response.Write("New text: " + txtBlah.Text + "<br />");
Session[btn.ID + "b"] = txtBlah.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["num"] = TextBox1.Text;
createStuff(true);
}
private void createStuff(bool btnClick)
{
PlaceHolder1.Controls.Clear();
int numBtn = Convert.ToInt32(Session["num"]);
for (int i = 0; i < numBtn; i++)
{
TextBox txtTemp = new TextBox();
txtTemp.Text = "old" + i;
txtTemp.ID = "txt" + "btn" + i;
PlaceHolder1.Controls.Add(txtTemp);
Button btn = new Button();
btn.Text = "btn" + i;
btn.ID = "btn" + i;
btn.Click += new EventHandler(test);
PlaceHolder1.Controls.Add(btn);
Session[btn.ID + "a"] = "meta" + i;
if (btnClick)
{
Session[btn.ID + "b"] = txtTemp.Text;
}
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
I think this is actually pretty decent and I am very happy with it. But, I know there have to be some improvements i can make since some of the tutorials on how the ASP postback system and object model or whatever its called are even now confusing me some.
any help or even just ideas are helpful thanks.
The only major improvement i can see is: use a UserControl, put the TextBox and Button inside, add properties (like OldValue/NewValue, stored in ViewState/TextBox) and add these UserControls to the PlaceHolder after you've created instances by using LoadControl.
The "MetaData" should also be stored as property in the UserControl. You should use Events to communicate between the UserControl and Page(f.e. TextSaved).
You can store the number of created controls in ViewState instead of the Session. That's the only thing you need to store in the Page. Append the index of the UserControl to it's ID.
General advantages of a Web User Control:
The biggest advantage of the Web User controls is that they can be created as a site template and used through out the site. For example they can be made to contain the Menu/Link structure of a site and can be used at all the other aspx pages.
This means the following :
If the website introduces a new site-wide link within the current layout/structure, it is enough if we put it on the user control once. All pages will be updated once if the web user control is used in them.
If there is any link to be corrected, it can be done once at the server side.
The .ascx files can either be used as a simple alternative to the plain HTML or they can also be used to respond to events: This means even custom code can be created against them and put in the code behind files.
http://www.dotnet-guide.com/usercontrol5.html
UserControls encapsulate complexity what is always good to increase
Reusability
Readability
Maintainability
Extensibility
... and to reduce the possibility of errors
Read this SO-answer for more examples.
ok i dunno if this is the right place for me to post back my newest code but i guess it would count as an "answer". also I want to say thank you so much for your answers they have been incredibly helpful. a little cryptic but fifty pages of tutorials or so later and yes your recomendations were fantastic so thank you and bravo. anyways heres my newest one that works perfectly with what I think are your recomended additions. if you want to take a peak and see if youd still do anything a little different or maybe in an easier way please feel free to let me know
first my user control "MyControl"
ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="DBtest.MyControl" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
ascx.cs:
//private String _oldText;
private String _metaData;
public String OldText
{
get
{
//return _oldText;
return (String)ViewState["OldText"];
}
set
{
//_oldText = value;
ViewState["OldText"] = value;
}
}
public String MetaData
{
get
{
return _metaData;
}
set
{
_metaData = value;
}
}
public String NewText
{
get
{
return TextBox1.Text;
}
set
{
TextBox1.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("My ID: " + this.ID + "<br />");
Response.Write("My Metadata: " + _metaData + "<br />");
Response.Write("My Old Text: " + ViewState["OldText"] + "<br />");
Response.Write("My New Text: " + TextBox1.Text + "<br />");
ViewState["OldText"] = TextBox1.Text;
}
then my page, aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TESTdynamicButton3.aspx.cs" Inherits="DBtest.TESTdynamicButton3" %>
<%# Register TagPrefix="uc" TagName="Spinner" Src="MyControl.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<hr />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<hr />
</asp:Content>
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
createStuff(false);
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["num"] = TextBox1.Text;
createStuff(true);
}
private void createStuff(bool btnClick)
{
PlaceHolder1.Controls.Clear();
int numBtn = Convert.ToInt32(ViewState["num"]);
for (int i = 0; i < numBtn; i++)
{
MyControl temp2 = LoadControl("MyControl.ascx") as MyControl;
temp2.ID = "uc" + i;
temp2.MetaData = "meta" + i;
//not sure why this DOES work, i would think it is overwritten each page load >.<
temp2.OldText = "old" + i;
if (btnClick)
{
temp2.NewText = "old" + i;
//not sure why this doesnt work below this line
//temp2.OldText = "old" + i;
}
//also not sure why this won't work
//temp2.OldText = temp2.NewText;
PlaceHolder1.Controls.Add(temp2);
}
}
and i also have a couple contents where im not sure it makes perfect sense why or do or dont use these lines to get the "old text" viewstate to populate properly initially. i would have thought i need to have that buttonclick check and only set the viewstate that first time to get it to work. also im not sure i understand why when i tried moving the createStuff() function to OnInit or the pre init functions overridden it wouldnt work..
thanks!
Leo
I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
I just found the answer and it works :)
You need to add the following to your server side link/button:
OnClientClick="aspnetForm.target ='_blank';"
My entire button code looks something like:
<asp:LinkButton ID="myButton" runat="server" Text="Click Me!"
OnClick="myButton_Click"
OnClientClick="aspnetForm.target ='_blank';"/>
In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.
The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
and
<body onload="fixform()">
You can use this as extension method
public static class ResponseHelper
{
public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;
if (page == null)
{
throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = #"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else
{
script = #"window.open(""{0}"", ""{1}"");";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
}
}
}
With this you get nice override on the actual Response object
Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10");
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);
Because Response.Redirect is initiated on the server you can't do it using that.
If you can write directly to the Response stream you could try something like:
response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");
The fixform trick is neat, but:
You may not have access to the code
of what loads in the new window.
Even if you do, you are depending on
the fact that it always loads, error
free.
And you are depending on the fact
that the user won't click another
button before the other page gets a
chance to load and run fixform.
I would suggest doing this instead:
OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"
And set up fixform on the same page, looking like this:
function fixform() {
document.getElementById("aspnetForm").target = '';
}
You can also use in code behind like this way
ClientScript.RegisterStartupScript(this.Page.GetType(), "",
"window.open('page.aspx','Graph','height=400,width=500');", true);
This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"
OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}
You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.
I always use this code...
Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
Here's a jQuery version based on the answer by #takrl and #tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:
<asp:Button ID="btnSubmit" OnClientClick="openNewWin();" Text="Submit" OnClick="btn_OnClick" runat="server"/>
Then in your js file referenced on the SAME page:
function openNewWin () {
$('form').attr('target','_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget(){
$('form').attr('target','');
}
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink>
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.
you can open new window from asp.net code behind using ajax like I did here
http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectionChanged += CalendarSelectionChanged;
}
private void CalendarSelectionChanged(object sender, EventArgs e)
{
DateTime selectedDate = ((Calendar) sender).SelectedDate;
string url = "HistoryRates.aspx?date="
+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"rates" + selectedDate, "openWindow('" + url + "');", true);
}
None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.
Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = "window.open('" + URL + "'); return false;"
I was having to modify someone else's response.redirect code to open in a new browser.
I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.
$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
$(".new-window").on("click", function () {
//--- change the form's target
$("#aspnetForm").prop("target", "_blank");
//--- change the target back after the window has opened
setTimeout(function () {
$("#aspnetForm").prop("target", "");
}, 1);
});
});
To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.
I did this by putting target="_blank" in the linkbutton
<asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" />
then in the codebehind pageload just set the href attribute:
btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)
HTML
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />
Javascript:
function SetTarget() {
document.forms[0].target = "_blank";}
AND codebehind:
Response.Redirect(URL);