using AutoPostBack doesn't work when setting input value in JS - asp.net

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.

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?

Devexpress GridLookup autopostback false causing page load

I am using ASPxGridLookup control and I set AutoPostBack="false" for that control, but when I changed the value the normal page life cycle is getting executed what is the solution for this.
<dx:ASPxGridLookup ID="ASPxGridLookup1" runat="server" KeyFieldName="ID" AutoPostBack="false">
</dx:ASPxGridLookup>
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dtLookup = new DataTable();
dtLookup.Columns.Add("ID");
dtLookup.Columns.Add("Name");
dtLookup.Rows.Add("1", "Dorababu");
dtLookup.Rows.Add("2", "Vivekh");
ASPxGridLookup1.DataSource = dtLookup;
ASPxGridLookup1.DataBind();
}
}
If you set AutoPostBack to false, changing ASPxGridLookup value initiates callback, not postback. Callback is a special kind of postback that skips some of lifecycle events and doesn't update ViewState.
DevEx: Discussion about Page.IsPostBack and Page.IsCallback values
DevEx: The Concept of Callbacks
Difference between a Postback and a Callback

How to test HiddenField Server Control's ValueChanged method

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)
{
}

Wiring events on dynamically-loaded ASP.NET User Controls?

For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via Page.FindControl gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
I've successfully loaded controls dynamically in Page_Load before. The only thing I found I had to be careful of was to ensure that if I did a postback, the same controls were loaded in subsequent page_load to ensure that the view state didn't get corrupted... all events etc worked as expected. In my case the controls flow ended up something like this:
page_load - load control a
(do something which causes postback and event x to fire)
page_load - make sure you load control a
event_x - clear control a, load control b
(do something which causes postback)
page_load - make sure you load control b
...
it meant loading controls you fully intented discarding, but was the only way I could find to not corrupt the viewstate...
If you have a page with PlaceHolder1 and Label1 in it, then the following code causes the button click event to fire just fine:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicButton = new Button() { Text = "Click me" };
dynamicButton.Click +=new EventHandler(dynamicButton_Click);
PlaceHolder1.Controls.Add(dynamicButton);
}
void dynamicButton_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked button";
}
Behaves the same with a user control:
WebUserControl ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
WebUserControl code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked Button";
}
parent control that loads the child control:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicControl = Page.LoadControl("~/WebUserControl.ascx");
PlaceHolder1.Controls.Add(dynamicControl);
}
Just FYI the issue had to do with validation; the events weren't firing properly because some of the validation controls (there were a ton) weren't configured to only apply to that control.

Databound Listview in UpdatePanel

I am using a Listview in a usercontrol that I databind to a list of object in the page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
BindListViews();
}
private void BindListViews()
{
MyListView.DataSource = IncludeExpressions;
MyListView.DataBind();
}
I need to handle inserting new items in the list.
To do that, I added an InsertItemTemplate with a button that has "Insert" as command argument.
I dont want to persist the data to the database until the user press the save button, at the bottom of the form.
So in the ItemCommand event, Here is my code:
protected void Expression_ItemCommand(object sender, ListViewCommandEventArgs e)
{
var listView = (sender as ListView);
var expressions = GetExpressions(listView);
var newExpression = new Expression
{
CaseSensitive = ((CheckBox)e.Item.FindControl("CaseSensitiveCheckBox")).Checked,
SearchText = ((TextBox)e.Item.FindControl("SearchTextTextBox")).Text,
Scope = (Scope)Enum.Parse(typeof(Scope), ((DropDownList)e.Item.FindControl("ScopeDropDownList")).SelectedValue, true),
Type = (Type)Enum.Parse(typeof(Type), ((DropDownList)e.Item.FindControl("TypeDropDownList")).SelectedValue, true),
};
expressions.Add(newExpression);
listView.DataSource = expressions;
listView.DataBind();
UpdatePanelInclude.Update();
}
private List<Expression> GetExpressions(ListView lv)
{
var expressions = new List<Expression>();
foreach (var row in lv.Items)
{
var searchText = ((TextBox)row.FindControl("SearchTextTextBox")).Text;
...
expressions.Add(new Expression
{
CaseSensitive = caseSensitive,
Scope = scope,
Type = type,
SearchText = searchText
});
}
return expressions;
}
This works perfectly fine until I add an UpdatePanel around the listview.
When I add an updatepanel, the Expression_ItemCommand handler is hit only every 2 clicks, eventhough the page is post back every click.
While debugging, I can see that I do enter the Page_Load event of the page at each click on the Insert button, but it hits the Expression_ItemCommand only every 2 clicks. and reset the content of my listview when the ItemCommand is not hit.
I smell ViewState problems here, but I can't figure out how to fix it.
Here is what the markup looks like :
<asp:UpdatePanel ID="UpdatePanelInclude" UpdateMode="Conditional" ChildrenAsTriggers="true" runat="server">
<asp:ListView ID="MyListView" OnItemCommand="Expression_ItemCommand" OnItemInserting="ExpressionInserting" OnDataBinding="ListViewDataBinding" InsertItemPosition="LastItem" runat="server" ItemPlaceholderID="itemPlaceHolder">
...
...
Any Idea how to solve this?
Stéphane
After looooong investigations and rebuilding of the page control by control, the reason was that the viewstate was compressed and the scriptmanager didnt like it somehow, even though I specify the hidden field to it.
Probleme solved...

Resources