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.
Related
I have a hidden field like this:
<asp:HiddenField ID="showHideFlag" runat="server" />
I am assigning some value to this hidden field in java script as follows:
function controlSearchBar() {
if ($("#MainContent_ProjectListControl_searchBar").is(":hidden")) {
$("#MainContent_ProjectListControl_showHideFlag")[0].value = "showing";
} else {
$("#MainContent_ProjectListControl_showHideFlag")[0].value = "hiding";
}
}
I am trying to read this hidden field in ascx.cs page as follows:
string hdnValue = this.showHideFlag.Value;
But this hdnValue is not getting the value of that hidden field.
Can someone help on this?
Hidden as type="hidden"
$("#MainContent_ProjectListControl_searchBar").attr('type') == 'hidden'
Hidden as display: none
$("#MainContent_ProjectListControl_searchBar").is(":hidden")
Gets the control ID for HTML markup that is generated by ASP.NET.
<asp:Label ID="SelectedSport" runat="server" ClientIDMode="Static" ClientID="showHideFlag">
javascript
$("#showHideFlag").text("found");
You are saying that you can get the value in javascript So I think the the problem is with the hidden field. try to set value by Client id as follows-
var hd = document.getElementById('<%= showHideFlag.ClientID%>');
hd.value = "hi";
And my another question is in which event you are accessing value? because If you are setting value in javascript and accessing in Page Load event then it will not work because first of all Page load event gets fired and then Javascript function executes.
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.
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 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
This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}