How to test HiddenField Server Control's ValueChanged method - asp.net

My understanding is that viewstate controls that hiddenfields or any other read only control have not been interfered with between postback on the client side.
But How do I come about checking this is actually working.
How can i simulate a postback with changed value in a hidden field to see what actually happen.
I have implemented a sub:
Protected Sub HF1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Handles HF1.ValueChanged
How can i test this? I tried inspect element in firefox but I cannot even find the hidden fields. I can see then on the page source but I cannot edit this.

I'm sure you're aware that changing the HiddenField will not post back automatically. Instead, it calls ValueChanged method when one of the server control post back.
Here is how you test - you can change the hidden field value at client side. Then click PostBack button to post back to server. HF1_ValueChanged will fire if hidden field is changed.
ASPX
<asp:HiddenField runat="server" ID="HF1" Value="1"
OnValueChanged="HF1_ValueChanged" />
<div id="button">Click this text to change Hidden Field</div><br/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"
Text="PostBack"/><br/>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function () {
$("#<%= HF1.ClientID %>").val("2");
alert("HF has new value: " + $("#<%= HF1.ClientID %>").val());
});
});
</script>
Code Behind
protected void HF1_ValueChanged(object sender, EventArgs e)
{
// This method should be called
// only if hidden field is changed at client side.
}
protected void Button1_Click(object sender, EventArgs e)
{
}

Related

how to store a label control text into a textbox control value

i am trying to set the value of a textbox control in my aspx page as the value of a label text. I am using the following code but nothing happens. I have tried from the code behind file using c# and then I want to assign the textbox value to a session variable. If I just assign a string value like "Hello"it works, but otherwise nothing works.
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
//Response.Redirect("booknow.aspx");
}
}
I also tried with Javascript, but no use:
var mtcid = parsedData.employeeCode;
document.getElementById('txtmtcid').value = mtcid;
The above js code works fine if I am assigning the value of mtcid to a label text, but not for the text box. please help.
You don't show things that could be messing this up.
and we can't see your markup used.
What does your page load event look like. Keep in mind that EVERY button click, post-back or ANY control on the page with a event code stub WILL RUN the page load event EVERY time. the page load event runs every time, and BEFORE your button click code runs.
So, if I have this markup:
<asp:Label ID="blbtest" runat="server" Text="zoo"></asp:Label>
<br />
<asp:TextBox ID="txtmtcid" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<br />
And then code behind of this:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
}
I then get this when I click on the button
So, we can see how the lable text is now copy to the text box.
You have to post more markup, and give futher detilas (such as some grid view, repeater or any other boatload of features that well explain your issue).
Note that you can double click on the button in the web forms designer to create a event click for the button. Its possible that no event code for the button exists, and your button click code and code behind never runs.
So this is the markup:
<asp:Label ID="blbtest" runat="server" ClientIDMode="Static">
</asp:Label>
<asp:Button ID="btnBook" runat="server" Text="Book Now"
CssClass="spaces-info__button" OnClick="btnBook_Click"/>
<asp:TextBox ID="txtmtcid" runat="server">
</asp:TextBox>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!(Session["username"] == null))
{
string usn = Session["username"].ToString();
lblusn.Text = usn;
}
}
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
Response.Redirect("booknow.aspx");
}
updated js:
$(function () {
//dom is ready
var request = new XMLHttpRequest;
var usn = document.getElementById('lblusn').innerHTML;
//var usn = "juhaina.ahmed";
console.log(usn);
request.open('GET', "URL" + usn + ""); //of course I have replaced
the URL here
request.onload = function () {
var response = request.response;
var parsedData = JSON.parse(response);
console.log(parsedData);
var nm = parsedData.fullName;
document.getElementById('lblfullnm').innerHTML = nm;
var mtcid = parsedData.employeeCode;
document.getElementById('blbtest').innerHTML = mtcid;
document.getElementById('txtmtcid').value =
document.getElementById('blbtest').innerHTML
};
request.send();
});
I am new to js, and asp.net, so trying to browse whatever possible and work things out here. The session variable value is just not getting passed to next page. Honestly, i dont need the textbox, I dont know if label text can be stored in session variables. If thats possible, then all I want to do is assign the blbtest label text to the session variable, but that also didnt work,but if I am hard coding it like:
Session["mtcid"]="D-11234"
this works and the value of session variable is passed.
hence I am trying now with textbox. Please let me know if theres a better approach to this.
If there is a way to avoid the use of the label and textbox and simply pass the session variable, Session["username"] from the code behind to the javascript, that would be great. how can I do it?

ASP:Button tag is onclick method is not calling

Button on click method is not calling
Button code :
<asp:Button ID="personalSub" runat="server" ValidationGroup="personal" Text="Save" CausesValidation="false" OnClick="InsertPersonalDetail" />
C# Code :
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello");
MessageBox.Show("hello");
}
If you have any problem on the page then you must see a compiler error.
You do NOT have compiler error witch is means that asp.net finds the InsertPersonalDetail function on code behind.
From what I see you call inside the button click two functions that are for desktop programming (not for web page).
Neither one can have any visible effect on your click - there is no console there to see anything, neither user interface to open the MessageBox.
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello"); // have no effect on web page
MessageBox.Show("hello"); // have no effect on web page
}
So its called but you don't see it by just wait a pop up to appears
To check this out, run it with debuger and add a break point there.
Or add a literal on page and add some text there to verify that is called.
eg, add on page
<asp:Literal runat="server" ID="txtLiteral" />
and on code behind
protected void InsertPersonalDetail(object sender, EventArgs e)
{
txtLiteral.Text += "InsertPersonalDetail called <br />";
}

using AutoPostBack doesn't work when setting input value in JS

I have a custom control which inherits from TextBox.
This allows me to use the TextBox's AutoPostBack property. This property makes the Page_Load method on the parent page fire when I change the value and click out of the text box.
I am setting the value of the rendered text box in JS as follows
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
When this code runs I am expecting the Page_Load method to run again.
I have tried things like
outputData.focus();
outputData.value = barcode.Value;
outputData.blur();
The code in the Page_Load is
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
}
}
So basically I am hoping to have whatever is in barcode.Value set on Label1.Text on the server.
All you need is to trigger onchange event for input since ASP.NET adds postback code to onchange attribute. The simplest way is calling onchange manually
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
outputData.onchange();
For more advanced techniques of simulating onchange event see this and this answers.
You can simply trigger the PostBack yourself with __doPostBack.
<asp:TextBox ID="CameraScannerTextbox1" runat="server" ClientIDMode="Static" AutoPostBack="true"></asp:TextBox>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<script>
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = '123456';
__doPostBack('CameraScannerTextbox1', '');
</script>
</asp:PlaceHolder>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
PlaceHolder1.Visible = false;
}
}
Not that I placed the javascript in a PlaceHolder that is hiddedn on PostBack, otherwise it will create a PostBack loop. But there are other ways to prevent that also.

asp:Button - onclick event fires code on a different code-behind?

I'm teaching myself to use a site.master page with child webforms embedded using the ContentPlaceHolderID object. I'm figuring it out, but I have one question; is it possible to put a button on the site.master page that fires code on the codebehind pages of the child forms? If I can do that, it will really simplify what I'm trying to accomplish.
I tried to 'inherit' both codebehinds, but of course that didn't work. Is there a way to do this?
Yes there is a way to do this. You need to set UseSubmitBehavior button property to false and then you can access the control that causes the post back using Request.Params.Get("__EVENTTARGET"); So the code would look like this:
Button definition in Site.Master markup:
<asp:Button ID="MyButton" runat="server" Text="Button" UseSubmitBehavior="false" />
code behind within any inherited page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// in case you have code to be executed on first load
}
else
{
string myButtonCtrl = Request.Params.Get("__EVENTTARGET");
if (myButtonCtrl != null && myButtonCtrl.EndsWith("MyButton"))
{
// MyButton has been clicked!
}
}
}

When this javascript function get called?

I have created one page.In that page,I wrote one javascript function for displaying character count,when user enter something in textbox.
protected void Page_Load(Object sender, EventArgs e)
{
TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
}
First time pageload,textbox is blank. Textbox does not have autopostback== true.After
pageload,user enter text into textbox.This time page is not loaded again.So when this function get called?
Page_Load will call everytime a page reloaded. so onkeyup will bind to the textbox everytime a page reloaded.
When this function get called?
This event is triggered when the user releases a Key while typing on TextBox1.
You can also bind it for the first time only:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
}
}
Or you can also bind it directly as:
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onkeyup="DisplayCharCount()">
</asp:TextBox>
The Page_Load method is called every time a user requests the page. The DisplayCharCount method is called whenever a user pressed a key (that is, release the key) in the TextBox1 element.

Resources