I have an html list to which I am trying to add html button to the property "innerhtml" using the code behind file. I am able to add the button however the onclick event is not getting fired
HTML:
<ul runat="server" id="list">
<li></li>
<li><a id="loginID" runat="server" href="../Accounts/login.aspx">Login</a></li>
<li id="logout" runat="server"> Register</li>
</ul>
code behind:
logout.InnerHtml = "<input type=\"submit\" id=\"b1\" runat=\"server\" onserverclick=\"b1_click\" />"; //logout is the id of the list item
}
}
public void b1_click(Object sender,EventArgs e)
{
Response.Redirect("~/Accounts/login.aspx");
}
}
This isn't the right way to dynamically create server-side controls.
Please review the example below to get a better understanding of how to do so. Keep in mind you can not assign the ClientID property as it is read only and initialized during runtime.
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Dynamic Button";
btn.ID = "b1"; // Server Side ID
btn.Click += b1_click;
logout.Controls.Add(btn);
}
public void b1_click(Object sender,EventArgs e)
{
Response.Redirect("~/Accounts/login.aspx");
}
Related
my x.aspx file :-
<form id ="Content3ret" runat="server">
</form>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"/>
my x.aspx.cs file :-
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
Content3ret.innerhtml = "<table id = '"+x+"'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
}
what I am trying to do is :-
when I click button each and every time there should be new radio button added with other .
like 3 button click I need 3 radio button .
but with this code when I click only one radio button creating .
like 3 click only one radio button with new id.
can anyone help me ?
When you add data on Content3ret.innerhtml and render them on the pages, this data are lost / gone / stay on page and never come back on post back - because this inner html is not post back with the second click on button.
So you have to render them on page, and at the same time saved it somewhere - preferable on viewstate because of asp.net
so the page will be like
<form id="form1" runat="server">
<div runat="server" id="divPlaceOnme"></div>
<asp:Button ID="Button1" runat="server" Text="ok" OnClick ="Button1_Click"/>
</form>
and on code behind we have
const string InnerHtmlKeeper_name = "InnerHtmlKeeper_cnst";
string InnerHtmlKeeper
{
get
{
var RetMe = ViewState[InnerHtmlKeeper_name] as string;
if (string.IsNullOrEmpty(RetMe))
return string.Empty;
else
return RetMe;
}
set
{
ViewState[InnerHtmlKeeper_name] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
// we keep the new with the previous data on this ViewState
InnerHtmlKeeper += "<table id = '" + x + "'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
// we add the final render on the div on page
divPlaceOnme.InnerHtml = InnerHtmlKeeper;
}
Last words.
Your approaches have many issues - and your code not working as it is. The button must be on the form, and you have to render inside some other div.
The point here is to show you have to save some actions on viewstate - beside that for a good solution on your problem you must use some javascript to render the radio without post back.
I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}
In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}
with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).
In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.
I am using an asp.net UpdatePanel that contains Button 1. On Button1 click, a string is created in code behind then sent back to the updatePanel. That string contains Button2 that should fire a postback to execute Button2_Click function. Unfortunately I haven't been able to execute a full postback on button 2 yet.
If I add Button2 as a PostBackTrigger control in the UpdatePanel on my aspx page I get an error that the control (Button2) is not found. This makes sense cause Buton2 is created by clicking Button1 in code behind and is not available on page load.
I'm trying to RegisterPostBackControl(Button2) on page load but again I get an error that Button2 doesn't exist in the current context.
Any help would be highly appreciated.
ASPX page
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<div runat="server" id="DIV1">Testing...<br /></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" clientidmode="static"/>
<div runat="server" id="DIV2"></div>
<asp:Label ID="DIV2_LABEL" runat="server"></asp:Label>
</fieldset>
</ContentTemplate>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(Button2);
}
protected void Button1_Click(object sender, EventArgs e)
{
string DIV1_Html;
DIV1_Html= DIV1.InnerHtml;
DIV2.InnerHtml = DIV1_Html;
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' runat='server' OnClick='Button2_Click' />";
}
protected void Button2_Click(object sender, EventArgs e)
{
DIV2_LABEL.Text = "Testing button2";
}
EDIT
Based on the advice below, I've added the button as follows:
Instead of:
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' runat='server' OnClick='Button2_Click' />";
I've amended the code as follows:
Button Button2 = new Button();
Button2.Text = "Add";
Button2.Click += new EventHandler(Button2_Click);
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = Button2.ID };
UpdatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(Button2);
BUT I'm still missing something because Button2_Click function is not fired when I click on the new button with NO error. ?????
Since your Button2 is created in client-side, It's ID is not recognized by the updatePanel1.
You can create Button2 dynamically like this:
Button button2 = new Button();
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = button2.ID };
updatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(button2);
UPDATE: Here is a little sample that you can use:
public partial class WebForm1 : System.Web.UI.Page
{
private bool ShowButton2()
{
return ViewState["createButton"] == null ? false : (bool)ViewState["createButton"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (ShowButton2())
CreateButton();
}
void CreateButton()
{
Button Button2 = new Button();
Button2.Text = "Add";
Button2.ID = "button2";
Button2.Click += Button2_Click;
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = Button2.ID };
updatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(Button2);
}
void Button2_Click(object sender, EventArgs e)
{
}
protected void button1_Click(object sender, EventArgs e)
{
if (!ShowButton2())
{
ViewState["createButton"] = true;
CreateButton();
}
}
}
The view state is a flag for showing Button2 of course.
There is a property on the button called OnClientClick, you can use that to call a javascript which then navigate to your page.
Example:
In your apsx page
<script type="javascript">
function reloadPage() {
window.location.href = '...';
}
In your code behind
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' OnClick='ReloadPage()' />";
I need to call a JavaScript method with parameters from the code behind.
Javascript method
<script type="text/javascript">
function changeControlSample(path)
{
$find('<%= PartialUpdatePanel7.ClientID %>').set_UserControlPath(path);
$find('<%= PartialUpdatePanel7.ClientID %>').refresh();
}
</script>
<iucon:PartialUpdatePanel runat="server" ID="PartialUpdatePanel7"
DisplayLoadingAfter="500" InitialRenderBehaviour="Clientside" EncryptUserControlPath="false">
<LoadingTemplate>
<div style="margin-left: 84px; margin-top: 10px;">
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/loading.gif" />
</div>
<div style="text-align: center">
Updating...
</div>
</LoadingTemplate>
</iucon:PartialUpdatePanel>
The code Behind of the page
protected Consultation controlconsultation = new Consultation();
protected void Page_Load(object sender, EventArgs e)
{
PartialUpdatePanel7.UserControlPath = "Espace_Candidat/Consultation.ascx";
controlconsultation.imageinfo += controlconsultation_imageinfo;
Session["controlconsultation"] = controlconsultation;
}
void controlconsultation_imageinfo(object sender, CommandEventArgs e)
{
PartialUpdatePanel7.UserControlPath = "Espace_Candidat/InfoEdition.ascx";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"CallMyFunction",
"changeControlSample('Espace_Candidat/InfoEdition.ascx')", true);
}
Code behind of the user control
public event CommandEventHandler imageinfo ;
protected void Page_Load(object sender, EventArgs e)
{
Consultation current = (Consultation)Session["controlconsultation"];
imageinfo = current.imageinfo;
}
protected void Valider (object sender, CommandEventArgs e)
{
if (imageinfo != null)
{
string pageNumber = (string)e.CommandArgument;
CommandEventArgs args = new CommandEventArgs("Control", pageNumber);
imageinfo(this, args);
}
}
This call didn't work even I change the JavaScript method by another one.
For example, if I try
Page.ClientScript.RegisterStartupScript
(this.GetType(),
"CallMyFunction",
"alert('blabla');",
true);
I got the same result.
So, What is the error that I commited?
How can I fix my code?
If you have update panel in page then call like this,
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), Guid.NewGuid().ToString(), #"<script type='text/javascript'>changeControlSample('" + path + "');</script>", false);
It don't have update panel then call like this
Page.ClientScript.RegisterStartupScript(this.GetType(), "tabselect", "<script type='text/javascript'>changeControlSample("' + path + '");</script>");
If you wish to call JavaScript method with parameters from the code behind you can get this done using
ClientScriptManager.RegisterStartupScript Method
please check the link given below:
http://msdn.microsoft.com/en-us/library/z9h4dk8y(v=vs.110).aspx
Hope this helps.
I am rendering some html in code behind using StringBuilder which includes a button. I am also trying to add a handler to this and I think perhaps not surprisingly it does not fire. Can I include an event handler to a button in this way?
sb.Append("<td>");
sb.Append("<input type='button' runat='server' id='butResetPassword' value='Reset Password' onserverclick='butSendEmail_Click' />");
sb.Append("</td>");
User.InnerHtml = sb.ToString();
this is the eventhandler that appears in the same code behind page
protected void butSendEmail_Click(object sender, EventArgs e)
{
labTester.InnerText = "Thanks for clicking me";
}
I answered a similar question of yours recently.
Unless you have a really good reason to generate markup in the code behind, keep it separate, otherwise stick to classic ASP.
You can do:
Markup:
<asp:Button runat="server" id="butResetPassword" OnClick="butSendEmail_Click" />
Code behind:
protected void butSendEmail_Click(object sender, EventArgs e)
{
//Reset the password here
labTester.InnerText = "Thanks for clicking me";
}
Edit* If all you need to do is display that confirmation message and not interact with any data or controls, then you could bind the button to a js function, change onserverclick to onclick:
<input type='button' runat='server' id='butResetPassword' value='Reset Password' onclick='butSendEmail_Click' />
And then have some js to handle this:
<script type="text/javascript">
function butSendEmail_Click() {
alert("Thanks for clicking me");
//Or set the labels text
var elem = document.getElementById("labTester");
elem.InnerHtml = "Thanks for clicking me";
}
</script>