Disabling a postback of a dynamic imageButton - c#

I have a table in an update panel. This table gets filled form the code behind and there is also a button added. This button triggers a Javascript. Because this button triggers a Javascript I don't need the button to do a postback. Is there a way to disable this postback?
This is the code I use to set the imagebutton in a table cell for each row.
ImageButton ibtnTableOneNewComment = new ImageButton();
ibtnTableOneNewComment.ImageUrl = "~/img/Pencil.png";
ibtnTableOneNewComment.OnClientClick = "setDiscription('test', 'testy')";
tabCell.Controls.Add(ibtnTableOneNewComment);
The table headers get set in the asp, the rest from the code behind.
<asp:UpdatePanel runat="server" ID="up_tableMain" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table runat="server" ID="tbl_main">
...Headers...
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>

Put return false; in your OnClientClick

You have to add return false; in the OnClientClick event of the button. This will block it to send any Postback request to Server:
ImageButton ibtnTableOneNewComment = new ImageButton();
ibtnTableOneNewComment.ImageUrl = "~/img/Pencil.png";
ibtnTableOneNewComment.OnClientClick = "setDiscription('test', 'testy'); return false;";
tabCell.Controls.Add(ibtnTableOneNewComment);

Related

ASP.Net - The validation error inside update panel disappears after dropdown item change

I have a submit form inside a update panel. If a user click on the submit button without filling any value, the validation message is shown on all the required fields.
Now, when user select or change an item from the dropdown control then all the validation message disappears. The dropdown control have AutoPostBack="true".
To resolve this I have tried to put all the dropdown control in one update panel and other controls in another panel but it didn't solve the problem.
You may try this in your update panel:
<asp:UpdatePanel ID="UP1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList ID Here" />
</Triggers>
<ContentTemplate>
</asp:UpdatePanel>
OR
By using JavaScript Code:
if (document.getElementById("<%=DropDownList ID.ClientID%>").value == "--SELECT--") {
alert('Your Message Here');
document.getElementById("<%=DropDownList ID.ClientID %>").focus();
return false;
}
else
{
return true;
}
You can call the Validaton of the form manually after the SelectedIndexChanged event of the DropDownList has completed.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// your code
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "validateForm", "setTimeout(function () { Page_ClientValidate(); }, 25);", true);
}
If you use a ValidationGroup, you need to specify it in the function: Page_ClientValidate('myGroup');
The only downside to this is that it will trigger ALL validators, not just the ones that have been activated by the user above the DropDownList that performs the PostBack.

HiddenField.ValueChanged Event not firing when changed from Javascript

UPDATE
I moved the Javascript to the ASPX site instead, and added a postback function for it. Now it works. Thanks to #orgtigger and especially #lucidgold for spending their time helping me!
Here is the update code that works!
<script type="text/javascript">
function changevalue(katoid) {
$('#<%=txtboxchosenkat.ClientID%>').val(katoid);
__doPostBack('<%= updpnlgridview.ClientID %>', '');
}
</script>
Code:
<asp:UpdatePanel ID="updpnlgridview" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtboxchosenkat" style="display:none;" runat="server" OnTextChanged="txtboxchosenkat_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:GridView ID="gridview" runat="server"></asp:GridView>
</ContentTemplate>
</asp:UpdatePane
Code-behind:
protected void hidfldchosenkat_ValueChanged(object sender, EventArgs e)
{
SqlConnection cn2 = new SqlConnection("Server=**,***,***,**;Database=******;
User Id=******;Password=******;");
SqlCommand cmd2 = new SqlCommand("SELECT * FROM tblProducts where KatID='" +
txtboxchosenkat.Text + "'", cn2);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.SelectCommand.CommandText = cmd2.CommandText.ToString();
DataTable dt = new DataTable();
da2.Fill(dt);
gridview.DataSource = dt.DefaultView;
gridview.DataBind();
}
The links (only part of code that makes links):
string line = String.Format("<li><a href='#' onclick='changevalue(" + pid + ");'>{0}",
menuText + "</a>");
Old Post
I need to update a GridView based on the value of a HiddenField. I am currently using a button to populate the GridView, but would like to do it automaticaly as soon as the value in the HiddenField changes.
But when I change the value with a javascript, then event doesn't fire.
(Same thing also happens in case of a TextBox and its OnTextChanged event.)
Not sure if this is way it's meant to work.
A Hidden field will not produce a postback (there is no AutoPostBack property), which means no postback will happen when the value of the hidden field has changed. However, when there is ANY postback from the page then OnValueChangd event will execute if a hidden field value has changed.
So you should try the following ideas:
1) Update your JavaScript for changevalue as follows:
function changevalue(katoid)
{
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid;
_doPostBack(); // this will force a PostBack which will trigger ServerSide OnValueChange
}
2) Change your HiddenField to a TextBox but set the Style="display:none;" and set AutoPostBack="true":
<asp:TextBox runat="server" ID="hidfldchosenkat"
Value="" Style="display:none;"
AutoPostBack="true" OnTextChanged="hidfldchosenkat_TextChanged">
</asp:TextBox>
This example works great for me:
JavaScript:
function changevalue()
{
$('#<%=hidfldchosenkat.ClientID%>').val("hi");
}
ASPX Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="hidfldchosenkat" runat="server" AutoPostBack="true"
ontextchanged="hidfldchosenkat_TextChanged"></asp:TextBox>
<asp:Button ID="Button1"
runat="server" Text="Button" OnClientClick="changevalue()" />
</ContentTemplate>
</asp:UpdatePanel>
C# Code-Behind:
protected void hidfldchosenkat_TextChanged(object sender, EventArgs e)
{
string x = "hi"; // this fires when I put a debug-point here.
}
Your issue could be with:
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid
You may want to try:
$('#<%=hidfldchosenkat.ClientID%>').val(katoid);
Also you should PUT changevalue() inside your ASPX JavaScript tags and not register it for every LinkButton.... so instead try the following:
protected void lagerstyringgridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Assuming the LinkButtons are on the FIRST column:
LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
if (lb != null)
lb.Attributes.Add("onClick", "javascript:return changevalue(this);");
}
}
You can have any event fire by doing a __doPostBack call with JavaScript. Here is an example of how I used this to allow me to send a hiddenfield value server side:
ASPX
<asp:HiddenField runat="server" ID="hfStartDate" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
JavaScript
$('#hfStartDate').val('send this');
__doPostBack('hfStartDate');
This will call the OnValueChanged event and cause a postback. You can also set this is a trigger for an update panel if you would like to do a partial postback.

Refresh The New Content With AJAX

In this example I want when the button with ID "PostCommentsButton" is pressed this ContentTemplate to be triggered and to iterate all again in ListView with ID "CommentListView". But this didn't work here. What I miss ?
In this example I take the new text from textfield and in code behind I put this new content from textfield with ado.net and I save this new content in database. The problem is that when the button in UpdatePanel is pressed the new information didn't come in the list with the other content. It comes only if I restart the page. I want ListView in UpdatePanel to be iterated again to take this new content from the textfield with AJAX when the button is pressed. What should I do ?
aspx code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="PostCommentsButton" />
</Triggers>
<ContentTemplate>
<asp:ListView ID="CommentListView" runat="server" DataSource= '<%# Eval("Comments") %>'>
<ItemTemplate>
<div class="postComments">
<span class="authorComment"><%# Eval("Author") %></span>
:
<span class="commentContent"><%# Eval("Message") %></span>
</div>
</ItemTemplate>
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
code behind :
protected void PostsListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//commandName is for recognize the clicked button
if (e.CommandName == "postComment")
{
//get the comment from textbox from current listview iteration
BlogProfileEntities blogProfile = new BlogProfileEntities();
var commentBox = e.Item.FindControl("AddCommentTextbox") as TextBox;
var hiddenFieldPostID = e.Item.FindControl("CurrentPostIDHiddenField") as HiddenField;
string text = commentBox.Text;
var postID = hiddenFieldPostID.Value;
Comment newComment = new Comment()
{
Message = text,
PostID = int.Parse(postID),
Author = Membership.GetUser().UserName
};
blogProfile.Comments.Add(newComment);
blogProfile.SaveChanges();
I dont see a text box in your example. If the text box is not in the update panel that gets called when the list view post back fires, I dont think you'll get the current value. I would suspect that if you put a break point on your commentBox variable, you would see it comes back as Nothing. If this isn't your full code, post everything.

Panel set to hidden and then visible loses textbox values

I hope I can explain this properly.
I have a grid that is part of our 3rd party shopping cart software. This grid has a row of quantity text boxes into which the customer enters how many of each thing they want to buy.
I put this grid inside a panel so I can set it on or off with
myPanel.Visible=true;
I also have a button to show and one to hide using the above code method.
If I enter a value into a textbox and then click the hide button and then click the show button, when the panel reappears the values are zero. If I then reload the page (browser reload) then the value returns as it was originally. It's a pretty good magic trick but not what I need. What am I doing wrong?
Eventually I want to select a date from a calendar while it is hidden but that is not in play yet... just the show/hide buttons.
Thanks
This sounds like the correct behaviour of ASP.NET WebForms and ViewState
First page load: Panel is visible and the panel loaded with its initial values.
Hide Panel: As soon as the button is pressed a post back occurs. myPanel is set to invisible which on the server side means that the HTML for the panel is not generated (this can be confirmed by looking the generated HTML).
Show Panel: A post back occurs again. But because the values were not rendered in the previous step, they are not available in the ViewState to repopulate the panel.
Reload of the page: This start the process over again (Same as step 1)
A possible solution is to instead hide the panel (<div) on the client-side. This will also have the benefit of not making a round trip to the server to just enable/disable the panel.
Your code should be like below...
Show and Hide button definition to show/Hide the panel is in Java script. That mans there is no handler of Button click event at server side...This approach is suggested normally and fast..
Sample ASPX Code
<script type="text/javascript" language="javascript">
function Hide() {
var ID = document.getElementById('pnl');
ID.style.display = 'none';
return false;
}
function Show() {
var ID = document.getElementById('btnHide');
ID.style.display = 'block';
return false;
}
</script>
<asp:panel id="pnl" runat="server">
<asp:GridView ID="grd" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="ed" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:panel>
<asp:button text="Hide" runat="server" id="Button1" onclientclick="return Hide();" />
<asp:button text="Show" runat="server" id="btnShow" onclientclick="return Show();" />
Sample Code Behind
public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataTable Dt = new DataTable())
{
using (DataColumn Dc = new DataColumn("Name"))
{
Dt.Columns.Add(Dc);
DataRow dr = Dt.NewRow();
dr["name"] = "1";
Dt.Rows.Add(dr);
dr = Dt.NewRow();
dr["name"] = "2";
Dt.Rows.Add(dr);
grd.DataSource = Dt;
grd.DataBind();
}
}
}
}
}

Ajax and simple button Event handlers not working

I am running into a problem with Ajax and C# asp.net. I am using Microsoft Visual Studio 2010.
First let me explain my web page.
I have script manager, and directly underneath that I have a update panel.
This is the dynamic placeholder I've been fiddling with.
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
Within my update panel, I have a dynamic control & a button.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<DBWC:DynamicControlsPlaceholder ID="DynamicControlsPlaceholder1"
runat="server">
</DBWC:DynamicControlsPlaceholder>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Now in my code behind:
I simply add 5 text boxes to a dynamic control. Page load;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["id"] = 0;
int id = (int)ViewState["id"];
for (int i = 0; i < 5; i++)
{
id++;
TextBox txt = new TextBox();
txt.ID = id.ToString();
DynamicControlsPlaceholder1.Controls.Add(txt);
txt.Text = i.ToString();
}
ViewState["id"] = id;
}
}
Now all my button does is add another TextBox to the dynamic control pannel.
protected void Button1_Click(object sender, EventArgs e)
{
int id = (int)ViewState["id"];
TextBox txt = new TextBox();
txt.ID = id.ToString();
DynamicControlsPlaceholder1.Controls.Add(txt);
// DynamicControlsPlaceholder1.DataBind();
txt.Text = id.ToString();
id++;
ViewState["id"] = id;
}
* Note I am using a custom dynamic control panel so their ID's are saved to the next page even though we have them creeated in a !Page.IsPostBack
The problem is that my button event handler only works once. I'm pretty sure its because the Ajax is calling a partial postback and it's not recognizing it to call my button event handler.
I'm not sure, any help is appriciated.
Firebug works wonders for debugging ajax. "There were multiple controls with the same ID '5'."
What a simple fix. Moved id++; to the top of Button1_Click event handler.
If you're ever assuming ajax is breaking your event handler just because the breakpoint is not firing in the event handler, firebug may save you too!
There was absolutely nothing wrong with the event handler, but the code within it was causing an error and ajax wasn't allowing it to break.

Categories

Resources