HiddenField.ValueChanged Event not firing when changed from Javascript - c#

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.

Related

How to add query parameters to a dopostback

I have a grid view that looks generally like this
<asp:GridView ID="MyGridView"
OnSelectedIndexChanged="OtherAddressGrid_SelectedIndexChanged"
OnRowDataBound="OnRowDataBoundOther"
<Columns></Columns>
</asp:GridView>
and on OnSelectedIndexChanged I want to change the postback url to add &TAB=something so that I can change the page to the selected tab using the Request.QueryString["TAB"]. To do this I set the onclick to a postback in OnRowDataBoundOther. This is what I have so far
protected void OnRowDataBoundOther(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(MyGridView, "Select$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}
question
How do I add custom parameters to this postback.
You can add your own select button to the Gridview that triggers the OnSelectedIndexChanged. You only have to add CommandName="select" to it in order to work. You also need to add a PostBackUrl to the button and a custom property that holds the value of TAB (in this snippet it is the row index)
<asp:Button ID="Button1" runat="server" Text="Select" CommandName="select"
data-item='<%# Container.DataItemIndex %>' PostBackUrl="~/Default.aspx?TAB=" />
You now have a button that looks something like this in HTML.
<input type="submit" name="GridView1$ctl05$Button1" value="Button"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl05$Button1", "", false, "", "Default.aspx?TAB=", false, false))"
id="mainContentPane_GridView1_Button1_3" data-item="3" />
As you can see aspnet added an onclick function to the button because you added a PostBackUrl. That function contains the url that will be used for PostBack. All we have to do now is change that url by adding the custom property with jQuery.
<script type="text/javascript">
$(document).ready(function () {
$('#<%=GridView1.ClientID %> input[type=submit]').each(function () {
var item = $(this).attr('data-item');
$(this).attr("onclick", $(this).attr("onclick").replace("?TAB=", "?TAB=" + item));
});
});
</script>

Textbox remembers its data on page refresh

I have 2 textbox on my page and a Button. When I click on a button, the text from the textbox is emailed. But, then when i refresh the page and no content is there, then also i get an email.
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text))
{
//email logic
TextBox1.Text = "";
TextBox2.Text = "";
}
else
{
//do nothing
}
}
Here, on clicking the button, i get an email but then when i refresh the page, even though there is no data, then also it goes inside the loop and i get an email.
How do i stop this ?
Do the following in your Page_Load event and keep your TextBoxes and Button in an <asp:UpdatePanel>. Then the page will not ask to re-submit each time you refresh the page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
}
UPDATE
Keep the controls within an UpdatePanel as follows
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Send mail" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You need to use the the POST > Redirect > GET pattern. Here is explanation link

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.

Accessing ASP HiddenField in javascript

I have been searching through here and google for a few days now, trying to figure out why I cannot get the value of a hiddenfield variable in javascript. When accessed, the value is returned as undefined.
I have an ASP HiddenField inside an UpdatePanel which is part of a custom user control in a .aspx web page (standard issue).
In my user control, I need to get the .Value of the HiddenField (hdnServer) in javascript after setting it in C#. But for some reason the following is not getting the correct value.
The MessageBox in the C# code returns the correct value (the code here has test values), but when accessed in javascript is undefined.
userControl.ascx:
//this function is called when the timer created in document.ready() elapses
//returns the correct hdnServer value in the check.
var checkHdn = function () {
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
temp = temp.toString();
if (temp != "") {
$('#LoadingViewer').hide();
clearInterval(checkSrv);
//enable start button
$('#startBtn').attr("Enabled", "true");
}
};
function RdpConnect() {
//serverName = undefined here. should be ip address when set in c#
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
alert(serverName);
if (serverName != "") {
MsRdpClient.Server = serverName;
}
};
userControl.ascx.cs code-behind:
public partial class userControl : System.Web.UI.UserControl
{
System.Timers.Timer timer;
protected void Page_Load(object sender, EventArgs e)
{
timer = new System.Timers.Timer(5000);
timer.Start();
}
protected void testOnTick(object sender, System.Timers.ElapsedEventArgs e)
{
hdnServer.Value = "test value";
startBtn.Enabled = true;
timer.Enabled = false;
}
}
Here is the asp for HiddenField just in case: userControl.ascx:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<!--trigger not used -->
<!-- <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />-->
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="hdnServer" runat="server" />
<asp:Label ID="Label1" Text="Loading, please wait." CssClass="loading" runat="server"
Font-Size="XX-Large" />
</ContentTemplate>
</asp:UpdatePanel>
Thank you for any advice in advance!
EDIT: messagebox removed..
Here is rendered html: http://pastie.org/3122247
You need to set ClientIDMode if you want to make it simple:
<asp:HiddenField runat="server" ClientIDMode="Static" Id="hidServer"/>
<script type="text/javascript">
alert($("#hidServer").val());
</script>
Or, use the ClientID property if you don't set ClientIDMode:
<asp:HiddenField runat="server" Id="hidServer"/>
<script type="text/javascript">
alert($("<%= hidServer.ClientID %>").val());
</script>
User controls have always been a strange issue for referencing using js and then master pages to go along with it.
For the hidden field do this:
<asp:HiddenField ID="hdnServer" runat="server" ClientIDMode="Static" />
in the js, do this:
var serverName = document.getElementById('hdnServer').value;
Try this:
var temp = $('#mytestcontrol_hdnServer').val();
you need to use ' not "
like:
var serverName = document.getElementById('<%= hdnServer.ClientID %>').value;
be careful don't use ". You have only use '
You can do this:
var temp = $('#hdnServer').val();
Instead of :
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
Also change this:
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
To this:
var serverName = $('#hdnServer').val();

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