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>
Related
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.
I'm trying to make my first ASP.NET web site and am unable to get searching and paging to work in ASP.NET Web Forms without using an invisible button. I can't use my search button's click event because it needs to reset my page to 0 when clicked, so it only has a client-click event. I have to make it call a JavaScript function, which calls the invisible button's click event handler after doing so. The only way I can figure out around it is to make the page post back to itself and pass the index in from the bottom paging table. Hopefully, someone here might have some suggestions for an easier way to do it. Thanks in advance for any suggestions. If it wasn't for paging, it would be one line of code inside my button click event handler.
Here is the relevant markup for my page.
<script language="javascript">
function page(index)
{
document.getElementById('PageIndex').value = index;
document.getElementById('btnInvisible').click();
}
</script>
<uc1:ucWidgetSearch runat="server" id="ctl" />
<p id="pHTML" runat="server"/>
<asp:Button ID="btnInvisible" runat="server" BackColor="White"
BorderStyle="None" BorderWidth="0px" OnClick="btnInvisible_Click" />
<asp:HiddenField ID="PageIndex" runat="server" /
Here is the markup for the UserControl on the page.
<label>Last Name:</label>
<asp:TextBox ID="txtLastName" runat="server" MaxLength="50" Enabled="false"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="page('0')" />
Here is the C# code behind for the .aspx page. The .aspx page uses no using statements.
namespace Widgets.WebUI
{ public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{ ScreenHelper.LoadScreen(ctl.Search(), pHTML, PageIndex);}
protected void btnInvisible_Click(object sender, System.EventArgs e)
{ }
}
}
Here is the code behind for the UserControl. It also uses no using statements.
public partial class ucWidgetSearch : System.Web.UI.UserControl
{
internal Widgets.BLL.WidgetSearch Search()
{
if (!txtLastName.Enabled)
{
txtLastName.Enabled = true;
txtLastName.Focus();
return null;
}
return new Widgets.BLL.WidgetSearch(txtLastName.Text);
}
}
Finally, there is a ScreenHelper class that calls into the BLL layer, which calls into the DAL layer and constructs an HTML document and passes it into the p element on the main page.
internal class ScreenHelper
{
internal static void LoadScreen(WidgetSearch search,
System.Web.UI.HtmlControls.HtmlGenericControl p, HiddenField page)
{
if (search != null)
{
try
{
p.InnerHtml = WidgetsLogic.GetHTMLTable(search.LastName, int.Parse(page.Value), 20);
}
catch (System.Exception ex)
{
p.InnerHtml = "<label style=\"color: #FF0000\">Error loading screen: " + ex.Message + "</label>";
}
}
}
}
namespace Widgets.BLL
{
public class WidgetsLogic
{
public static string GetHTMLTable(string name, int pageIndex, int? pageSize)
{
StringBuilder strBuilder = new StringBuilder("<table border=\"1\">");
List<Widget> list = WidgetsDataAccess.GetByName(name);
int minDex = 0, maxDex = list.Count;
if (pageSize == null)
{
pageIndex = 0;
}
else
{
pageIndex = HTMLHelper.GetPageIndex(pageIndex, pageSize.Value, list.Count);
minDex = pageIndex * pageSize.Value;
maxDex = minDex + pageSize.Value;
if (maxDex > list.Count)
maxDex = list.Count;
}
for (int i = minDex; i < maxDex; i++)
{
strBuilder.Append("<tr");
// Set Light Gray Color for alterating rows in table
if (i%2 != 0)
strBuilder.Append(" style=\"background-color: #EBEBEB\"");
strBuilder.Append("><td>" + list[i].ID.ToString() + "</td>");
strBuilder.Append("<td>" + list[i].Name + "</td></tr>");
}
strBuilder.Append("</table>");
// Add Paging if appropriate
if (pageSize != null && pageSize.Value < list.Count)
{
strBuilder.Append(HTMLHelper.GetPagingFooter(pageIndex, pageSize.Value,
list.Count, "javascript:page('#pageIndex')"));
}
string str = strBuilder.ToString();
return str;
}
}
you should never try to do paging manually. Rather use GridView and an ObjectDataSource
to bind data to your page. This way ASP.NET handles the pageIndex exc via viewstate and the ObjectDatasource handles paging for you.Check this link for a good example of how to do just that.
Use ClientID to refer to the actual ID of an HTML control
document.getElementById('<%= PageIndex.ClientID %>').value = index;
when I click on the following button it opens up the page twice. I can not seem to find the error:
the .cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
btnPrint.Attributes.Add("onclick", "openWindow(" + Request.QueryString["cId"].ToString() + "," + Request.QueryString["aId"].ToString() + ");");
}
}
The javascript:
<script type="text/javascript">
//Function To Open A New Window To View the selected PDF
function openWindow(cId, aId) {
window.open("printMe.aspx?cId=" + cId + "&aId=" + aId + "", "", "", "");
}
</script>
and the button in the aspx:
<dx:ASPxButton ID="btnPrint" runat="server" Image-Url="~/images/print.bmp" ToolTip="Printer Friendly Page">
</dx:ASPxButton>
changing the javascript like below fixed the problem. I am no expert at javascript.
<script type="text/javascript">
//Function To Open A New Window To View the selected PDF
function openWindow(cId, aId) {
window.open("printMe.aspx?cId=" + cId + "&aId=" + aId,"mywindow");
}
</script>
I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.
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