Hidden field not getting set Ajax AutoCompleteExtender OnClientItemSelected - c#

I'm trying to use the following Ajax AutoCompleteExtender:
<asp:TextBox runat="server" Width="300" ID="tbxItem" CssClass="NormalUpper" />
<asp:AutoCompleteExtender ID="autoCompleteExtenderItemName" runat="server"
MinimumPrefixLength="1" ServicePath="../Services/AutoCompleteSpecialOrders.asmx"
ServiceMethod="GetItems" CompletionInterval="100"
Enabled="True" TargetControlID="tbxItem" CompletionSetCount="15" UseContextKey="True"
EnableCaching="true" ShowOnlyCurrentWordInCompletionListItem="True"
CompletionListCssClass="dbaCompletionList"
CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListItemCssClass="AutoExtenderList" DelimiterCharacters="">
OnClientItemSelected="ItemSelected"
</asp:AutoCompleteExtender>
<asp:HiddenField runat="server" ID="hiddenItemId" />
We're using Master Pages (asp.net 4.0), User Controls and UpdatePanels. I'm having difficulty getting the OnClientItemSelected="ItemSelected" JavaScript/Jquery function to work. Here is the ScriptManagerProxy:
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" >
<Scripts>
<asp:ScriptReference Path="../common/script/AutoExtend.js"/>
</Scripts>
</asp:ScriptManagerProxy>
And here is the contents of AutoExtend.js (JavaScript & Jquery):
//function ItemSelected(sender, eventArgs) {
// var hdnValueId = "<%= hiddenItemId.ClientID %>";
// document.getElementById(hdnValueId).value = eventArgs.get_value();
// alert(hdnValueId.value);
// document.getElementById("tbxCatalogQty").focus();
// This try didn't work for me}
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
alert(hdnValueId.value);
document.getElementById("tbxCatalogQty").focus();
} //Neither did this one.
The alert DOES show the correct value from our WebService drop-down-type list! I just can't seem to set the hidden field to this value so I can use it in the code-behind later. It always shows as "" when run in the debugger. Also, the .focus() method doesn't set the focus to the tbxCatalogQty field like I would like. I've also tried this with single-quotes and that didn't change anything either.
In my code behind, I've tried accessing the hidden field as follows without any luck:
//var itemId = Request.Form[hiddenItemId.Value];
var itemId = hiddenItemId.Value;
I've seen a couple of similar posts out there: 12838552 & 21978130. I didn't see where they mentioned anything about using Master Pages and User Controls and inside of an UpdatePanel (not sure that makes any difference, however).

With the help of a friend, he just figured out the solution. First, we did a JavaScript postback, passing in the value like this:
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
window.__doPostBack('UpdatePanelOrdersDetails', hdnValueId.value);
}
Then, in the ASP:Panel that contained the AutoCompleteExtender, we added the "Onload="pnlInputCat_Load" parameter.
<asp:Panel ID="pnlInputCat" runat="server" OnLoad="pnlInputCat_Load">
Then, in the code behind, we added the pnlInputCat_Load method to look like this:
protected void pnlInputCat_Load(object sender, EventArgs e)
{
var theId = Request["__EVENTARGUMENT"];
if (theId != null && !theId.Equals(string.Empty))
{
Session["ItemCode"] = Request["__EVENTARGUMENT"];
tbxCatalogQty.Focus();
}
}
There certainly might be better ways to make this work, but I now have the ItemCode in a session variable for later access and I could then set focus on the Catalog Qty textbox.
Thanks for anyone who tried to understand/answer the above question.

Related

Pass C# variable through URL

I have defined a variable in C# as the item selected in a drop down.
string parametername = ddlCarrier.SelectedItem.Text;
I now want to pass this variable in my URL to the next page. How do I do this in the href tag?
<asp:LinkButton href="Table.aspx?parameter=<%parametername%>" ID="btnSubmit" runat="server">Click Here</asp:LinkButton>
Purely Server-Side Approach
Instead of a LinkButton, you might want to consider using a HyperLink or <a> tag as you aren't going to be doing anything with your code-behind:
<asp:HyperLink ID="btnSubmit" runat="server" NavigateUrl="Table.aspx" Text="Navigate"></asp:HyperLink>
Then you can use the NavigateUrl property, which you might want to consider setting within your code-behind :
// This will set up your Navigation URL as expected
btnSubmit.NavigateUrl = String.Format("Table.aspx?parameter={0}",ddlCarrier.SelectedItem.Text);
If you use this approach, you may want to explicitly set that a PostBack occurs when your DropDownList changes so that this value will consistently be correct :
<asp:DropDownList ID="dllCarrier" runat="server" AutoPostBack="True" ...>
Client-Side Approach
However, if you are expecting to be able to change this to reflect the current value of your Carrier DropDownList without a PostBack, then you'll likely need to resort to Javascript to populate the value prior to actually navigating :
<!-- Set your base URL within the method and append the selected value when clicked -->
<asp:Button ID="Example" runat="server" OnClientClick="ClientSideNavigate('Table.aspx'); return false;" Text="Navigate"></asp:Button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
Or you could just avoid ASP.NET Controls altogether and just use an <button> tag :
<button onclick="ClientSideNavigate('Table.aspx'); return false;">Navigate</button>
<script>
function ClientSideNavigate(url) {
// Get the selected element
var e = document.getElementById('<%= ddlCarrier.ClientID %>');
// Navigate
window.location.href = url + '?parameter=' + e.options[e.selectedIndex].value;
}
</script>
You need to handle TextChanged or SelectedIndexChanged event for ddlCarrier and properly set href property of btnSubmit to include ddlCarrier.Text.

Fire Serverside event from javascript

i have hiddentfield whose value is changing on javascript.
I just wanted to fire serverside event valuechanged event of hiddenfield when its value changed from javascript.
I tried with :
__doPostBack('hfLatitude', 'ValueChanged');
But giving me error :
Microsoft JScript runtime error: '__doPostBack' is undefined
Is there any other alternative for this?
Please help me.
In javascript, changes in value to hidden elements don't automatically fire the "onchange" event. So you have to manually trigger your code that is already executing on postback using "GetPostBackEventReference".
So, with a classic javascript approach, your code should look something like in the example below.
In your aspx/ascx file:
<asp:HiddenField runat="server" ID="hID" OnValueChanged="hID_ValueChanged" Value="Old Value" />
<asp:Literal runat="server" ID="litMessage"></asp:Literal>
<asp:Button runat="server" ID="btnClientChage" Text="Change hidden value" OnClientClick="ChangeValue(); return false;" />
<script language="javascript" type="text/javascript">
function ChangeValue()
{
document.getElementById("<%=hID.ClientID%>").value = "New Value";
// you have to add the line below, because the last line of the js code at the bottom doesn't work
fValueChanged();
}
function fValueChanged()
{
<%=this.Page.GetPostBackEventReference(hID, "")%>;
}
// the line below doesn't work, this is why you need to manually trigger the fValueChanged methiod
// document.getElementById("<%=hID.ClientID%>").onchange = fValueChanged;
</script>
In your cs file:
protected void hID_ValueChanged(object sender, EventArgs e)
{
litMessage.Text = #"Changed to '" + hID.Value + #"'";
}
Quick and Dirty:
Simply put a asp button on form. Set it display:none.
<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />
On its click event call any server side event.
protected void xyx_Click(o,e)
{
//you server side statements
}
To call its from JS use as below:
<script>
function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}
function anyotherjsfunc()
{
//some statements
myserverside_call();
}
</script>
First way is to use HiddenField.ValueChanged Event.
If you want to also watch this varible in Client Side just use this:
$('#hidden_input').change(function() {
alert('value changed');
});
Second way is to assign value to Varible:
$('#hidden_input').val('new_value').trigger('change');

How to get dropdown list selected value in Label without using autopostback and update panel in asp.net

How to get dropdown list selected value in Label without autopostback and update panel in asp.net. i want the client side scripting for this code
i have the following code :-
protected void DropDownList1_TextChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
// DropDownList1.Attributes["onclick"] =
//"Label1.Text=this.options[this.selectedIndex].value";
}
If you don't want to use jquery (not everyone does! :) ) you can do it with standard javascript
<script language="javascript" type="text/javascript">
function setLabelText() {
var dropdown = document.getElementById("DropDownList1");
document.getElementById("Label1").innerHTML = dropdown.options[dropdown.selectedIndex].text;
}
</script>
<asp:DropDownList ID="DropDownList1" ClientIDMode="Static" runat="server" AutoPostBack="false" onchange="setLabelText();">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two" />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Label" ClientIDMode="Static"></asp:Label>
In your CS code, add an attribute such as:
ddlMyDrop.attributes.add("onchange","SetLabel(this,lblCtrl)");
In your JS code...
function SetLabel(sender, target){
$(target).val($(sender).val());
}
This assumes you reference jQuery.
You can do this fairly easily with jQuery. Label's turn into span and DropDownList into select on client side. Keep in mind that asp.net loves to append strings to the resultant content id's, e.g. MainContent_...
$(document).ready(function () {
$('#MainContent_DropDownList1').change(function () {
try {
$('#MainContent_Label1').text($(this + "option:selected").text());
} catch (err) {
alert(err);
}
});
});
Not using jQuery or Javascript as this is a fix of an existing site and it was not designed that way. Well I have gotten to a point where when the DropDownList is selected and does it's postBack I do my logic of setting the textBox readOnly status to true or false. the problem I have now is the the selectValue is not consistant. Wht it show in the selct field is not what is posted back to the page. Say I have None, 5.00, 10.00, 15.00, 20.00 as my choices to choose. I first choose 10.00 and it posts back None then I choose 20.00 it shows 10.00. It posts back the prior select value. the entire site is written from the code behind page. the aspx page is completely written from the .vb page. Everything is written into asp tags. here is the code;
If Page.IsPostBack Then
If product_option_is_required > 0 then
myTextBox.ReadOnly= true
Else
myTextBox.ReadOnly= false
End if
For Each child_control As Control In productOptions.Controls
If TypeOf child_control Is DropDownList Then
Dim child_ddl As DropDownList = child_control
tempName = products.getProductDependant("product_option_name",product_option_id)
tempSelectText = products.getProductSelectDependant("product_option_detail_name",child_ddl.SelectedValue)
priceDependant.Text ="here" & child_ddl.ID & " " & child_ddl.SelectedIndex & " " & child_ddl.SelectedValue & " --" & tempSelectText
If child_ddl.Text = "None" then
myTextBox.ReadOnly = true
myTextBox.Text = "If selected above enter name"
Else
myTextBox.ReadOnly = false
myTextBox.Text = ""
End if
End If
next
End if

Using onCheckedChanged with PopupControlExtender and want to prevent popup when unchecking

I am still reasonably new to this and have tried to find an answer, so hopefully I am not repeating this.
I am using ASP.NET and have a checkbox control that brings up a popup box when it's changed, using the onCheckedChanged method. This popup box has some info in it and a 'Close' button which successfully closes the popup.
What I want is to prevent the popup appearing if the checkbox is being unchecked. I currently have the onCheckedChanged calling a code behind method which cancels the extender call if the control is not checked, but the popup quickly appears before it is closed. How can I prevent it this?
This is the appropriate page code:
<div class="row" id="divDDMandate" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="chkDDMandate" Width="20px" Visible="true" runat="server" AutoPostBack="true"
OnCheckedChanged="clientchkDDMandateChanged(this);" on />
<asp:Literal ID="ltlDDMandate" runat="server">Direct Debit Mandate (by post)</asp:Literal>
<asp:PopupControlExtender ID="chkDDMandate_PopupControlExtender" runat="server"
DynamicServicePath="" Enabled="true" PopupControlID="PanelDDMandateDownload"
TargetControlID="chkDDMandate"
Position="Bottom" OffsetX="-20" OffsetY="10" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
...and this is my code behind method:
protected void chkDDMandateChanged(object sender, EventArgs e)
{
//Cancel the panel if unchecking
if ((!chkDDMandate.Checked) && chkDDMandate_PopupControlExtender.Enabled)
{
chkDDMandate_PopupControlExtender.Cancel();
}
}
I would be grateful for any help.
Cheers
Remove AutoPostBack="true" from the chkDDMandate checkbox and add script below after the ScriptManager control:
<script type="text/javascript">
function pageLoad() {
var extender = $find("<%= chkDDMandate_PopupControlExtender.ClientID %>");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var checkBoxChecked = $get("<%= chkDDMandate.ClientID %>").checked;
args.set_cancel(!checkBoxChecked);
}
</script>
After Yuriy provided me with the event handler, I had to resort to using hidden fields to keep track of the visibility of the popup and the checkbox.
This was because I didn't want the popup to appear when the tick was being removed and the fact that the onClick method used the setting the checkbox control was being set to, whereas the onShowing method was using the current visible setting of the control. I had to use the hidden fields to keep the visibilty settings and update them at the time I wanted.
I'm surprised that the _visible property of the popup extender was always set to 'false', so I couldn't use that either.
This may be a bit of a hack, but this is my current javascript code for anyone that is interested:
<script type="text/javascript">
function pageLoad() {
// Attach an event handler for over-riding the showing Popup.
var extender = $find("PopupControlExtenderBehaviorID");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
// Initialise the hidden fields based on the page status after refresh.
var hfPopup = $get("ctl00_body_PopupVisibleID");
var hfCheckbox = $get("ctl00_body_CheckboxChecked");
// Popup will always be hidden on page refresh
hfPopup.value = "Hidden";
hfCheckbox.value = $get("ctl00_body_chkDDMandate").checked;
}
function onPopupShowing(sender, args) {
// This function will over-ride the Popup showing if applicable.
var popupVisible = $get("ctl00_body_PopupVisibleID");
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
// If Popup hidden and 'tick' being taken out of the Checkbox, don't show the Popup.
if (popupVisible.value == "Hidden" && checkboxChecked.value == "true") {
args.set_cancel(true);
}
else if (popupVisible.value == "Hidden") {
popupVisible.value = "Visible";
}
else {popupVisible.value = "Hidden";}
}
function OnClientClickCheck(o) {
// This function will set the Hidden field value of Checkbox.
// This is because when the OnClick method reads the control checkbox value it uses the value it's
// being set to; whereas, the onPopupShowing method uses the value it is currently displaying!
var pce = $find('PopupControlExtenderBehaviorID');
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
var isChecked = o.checked;
if (isChecked) {
// isChecked is what it is being changed to...
checkboxChecked.value = "false";
}
else {
checkboxChecked.value = "true";
}
pce.showPopup();
}
</script>
Thanks for the help in getting here.

How to get the 'controlToValidate' property on ClientValidationFunction?

Lets say I have this code.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="ValidationFunction1"
ControlToValidate="TextBox1"
Display="Dynamic" />
And a validationFunction:
function ValidationFunction1(sender, args)
{
}
And i would like to know if, inside the function I could get the Control to validate something like:
var v = sender.ControlToValidate;
Actually sender.controltovalidate gives the ClientID of the control. So this seems like a solution.
function ValidationFunction1(sender, args){
var v = document.getElementById(sender.controltovalidate);
}
I tried and it worked for me. Please notify if it works.
Not verified, just a hint:
var v = document.getElementById('<%=CustomValidator1.FindControl(CustomValidator1.ControlToValidate).ClientID>%');
of course you could simply do it like:
var v = document.getElementById('<%=TextBox1.ClientID%>');
if you know exactly what you're validating. The first method is good when the control to be validated is set dynamically and you don't know beforehand which one it will be.
Also FindControl() might return null so you'd need to test for that too in order to avoid an exception.
Hope this helps.
Here's my take on a server-side solution in C# to mimic the above answer, for anyone interested:
<asp:TextBox ID="txtStudentComments" runat="server"
Rows="8" Width="100%"
ToolbarCanCollapse="False" ValidationGroup="vg1" />
<asp:CustomValidator ID="cv1" runat="server" ControlToValidate="txtStudentComments"
ErrorMessage="THESE COMMENTS DO NOT SEEM RIGHT. PLEASE REVIEW THEM AGAIN!" SetFocusOnError="true"
Font-Bold="True" Font-Size="Medium" ValidationGroup="vg1" OnServerValidate="cv1_ServerValidate"></asp:CustomValidator>
And on the server:
//validate of the comment contains some specific words which imply the TET has not reviewed the comments!
protected void cv1_ServerValidate(object source, ServerValidateEventArgs args)
{
CustomValidator cv = (CustomValidator)source;
GridViewRow gvRow = (GridViewRow)cv.NamingContainer;
TextBox editor = (TextBox)gvRow.FindControl("txtStudentComments");
if (editor.Text.ToUpper().Contains("FACILITATOR TO INSERT COMMENTS HERE PLEASE"))
args.IsValid = false;
else
args.IsValid = true;
}
These two lines are the crux of it.
CustomValidator cv = (CustomValidator)source;
GridViewRow gvRow = (GridViewRow)cv.NamingContainer;
The NamingContainer will be a GridViewRow in my case, but it could be your entire page depending on your program. Either way it allows me to find the control I want, relative to the ControlToValidate object, which as mentioned will return the ClientID.
Here's my easy solution to be able to access the control to validate on client side.
Add the regular Custom Validator control with the options you might need.
<asp:CustomValidator ID="cvalShippingRegionCountries" ErrorMessage="Choose a country" ClientValidationFunction="ClientValMultiSelectCountries" runat="server" Display="Dynamic" SetFocusOnError="true" />
Then, in code behind, just add a custom attribute to store the clientID of the control to validate.
cvalShippingRegionCountries.Attributes.Add("ControlToValidateClientID", multiselectShippingRegionCountries.ClientID);
Now, in the function that deals with the validation you can access the value like this:
function ClientValMultiSelectCountries(sender, args) {
var multiselect = $find(sender.attributes.controltovalidateclientid.nodeValue);
if ( #VALIDATION_CHECK_HERE# ) {
args.IsValid = false;
}
}
You will get the clientID inside your function ;)

Categories

Resources