Yet another viewstate dropdownlist issue - c#

I have the following code in the Page_Load method of a web form:
protected void Page_Load(object sender, EventArgs e)
{
CountrySelectButton.Click += new EventHandler(CountrySelectButton_Click);
if (HomePage.EnableCountrySelector) //always true in in this case
{
if(!IsPostBack)
BindCountrySelectorList();
}
}
The BindCountrySelectorList method looks like this:
private void BindCountrySelectorList()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(HomePage.CountryList);
var ds = nvc.AllKeys.Select(k => new { Text = k, Value = nvc[k] });
CountrySelector.DataSource = ds;
CountrySelector.DataTextField = "Text";
CountrySelector.DataValueField = "Value";
CountrySelector.DataBind();
}
And I have a LinkButton click event handler which gets the SelectedValue from the SelectList as so:
void CountrySelectButton_Click(object sender, EventArgs e)
{
//get selected
string selectedMarket = CountrySelector.SelectedValue; //this is always the first item...
//set cookie
if (RememberSelection.Checked)
Response.Cookies.Add(new HttpCookie("blah_cookie", selectedMarket) { Expires = DateTime.MaxValue });
//redirect
Response.Redirect(selectedMarket, false);
}
EDIT:
This is the DDL and LinkButton definition:
<asp:DropDownList runat="server" ID="CountrySelector" />
<asp:LinkButton runat="server" ID="CountrySelectButton" Text="Go" />
Resulting markup:
<select name="CountrySelector" id="CountrySelector">
<option value="http://google.com">UK</option>
<option value="http://microsoft.com">US</option>
<option value="http://apple.com">FR</option>
</select>
<a id="CountrySelectButton" href="javascript:__doPostBack('CountrySelectButton','')">Go</a>
END EDIT
ViewState is enabled but the SelectedValue property only ever returns the first item in the list regardless of which item is actually selected. I'm certain I'm missing something obvious but I can't find the problem; any help is much appreciated.
Thanks in advance.
Dave

You are correct that your issue stems from the jquery ui dialog... you can get around this by using a hidden field to record the value of the dropdownlist. Then in your code, reference the hidden field.
Front end could look like:
<div id="myModal" style="display: none;">
<asp:DropDownList runat="server" ID="SelectList" />
<asp:LinkButton runat="server" ID="MyButton" Text="Go" />
</div>
<input type="hidden" id="countryVal" runat="server" />
<a id="choose" href="#">Choose</a>
<script type="text/javascript">
$(document).ready(function () {
$('#choose').click(function () {
$('#myModal').dialog({
});
return false;
});
$('#<%= SelectList.ClientID %>').change(function () {
var country = $(this).val();
$('#<%= countryVal.ClientID %>').val(country);
});
});
</script>
Then your code behind:
var selected = countryVal.Value;

Wrap the MyButton.Click+=... statement inside (!IsPostBack) like
if(!IsPostBack)
{
MyButton.Click += new EventHandler(MyButton_Click);
BindSelectList();
}

Related

Using label text in linq where parameter

Basically i tried to do what is recommended but somehow it doesn't work. the problem is i cannot take value of selected item in dropdown to textbox value. what i observed is JS code isn't triggered. What could be the problem?
my codes are;
HTML
<div class="dropdown show col-md-2 p-1">
<a class="btn btn-secondary btn-sm dropdown-toggle p-1" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" runat="server">Load Evaluation
</a>
<div id="dropdown" runat="server" class="dropdown-menu" aria-labelledby="dropdownMenuLink">
</div>
</div>
<div>
<asp:TextBox ID="dropLabel" runat="server" AutoPostBack="true" OnTextChanged="dropLabel_OnTextChanged" Style ="display:block"></asp:TextBox>
</div>
JS
$('#dropdown a').on('click', function () {
$('#dropLabel').val(this.text());
sessionStorage.setItem('label1', $(this).text());
location.reload(true);
})
C#
protected void dropLabel_OnTextChanged(object sender, EventArgs e)
{
var labelText = (sender as TextBox).Text;
//... do something with the text.
A3toSqlDataContext ctx4 = new A3toSqlDataContext();
var yukle = from c in ctx4.A3_Coaching
where c.name == labelText
select c;
C# for a tag including
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
A3toSqlDataContext ctx = new A3toSqlDataContext();
var alp = from c in ctx.A3_Coaching
select c.name;
foreach (var item in alp)
{
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "#");
anchor.InnerHtml = Convert.ToString(item);
anchor.Attributes.Add("class", "dropdown-item");
dropdown.Controls.Add(anchor);
}
}
}
The problem is, that your dropLabel might be a server-side control, but the actual javascript is happening on the client, so your asp.net application will not be aware of this until you do a postback to the server.
You should be able to do this, if you convert your droplabel to an invisible Textbox, that will do a Postback for you, when its text changes:
<div>
<asp:Textbox id="dropLabel" runat="server"
AutoPostback="true"
OnTextChanged="dropLabel_OnTextChanged"
style="display:none">
</asp:Textbox>
</div>
CodeBehind:
protected void dropLabel_TextChanged(object sender, EventArgs e)
{
var labelText = (sender as TextBox).Text
//... do something with the text.
}
Make sure you check for a PostBack in your Page_Load to not re-load everything and possibly overwrite your state using if(!IsPostBack) { /*... do regular Page_Load*/}

How to get a radio button excluyent in a repeater element?

I have a repeater using for getting an image nad a radio button on the bottom. I want to achieve a combination of this radio button (repeater speaking) with the property of autoexcluyent feature. How can I achieve it?
As far as I got ...
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
With this code I am getting a one radio button per each image but no one autoexcuyent even I am using GroupName property
USING NET FRAMEWORK 4.6.2.
I don't know if easy way to manage this situation however you can manage by below code. It will be good to wrap your contents into update panel so you can prevent page refresh on checkbox changed.
Additionally, IsChecked property being used to initialize checked on page load. You can remove if not required.
.ASPX
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<span>
<asp:RadioButton runat="server" ID="rb1" Checked='<%# Eval("IsChecked") %>' AutoPostBack="true" OnCheckedChanged="rb1_CheckedChanged" Text='<%#Eval("description").ToString()%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<test1> lst = new List<test1>();
lst.Add(new test1() { Id = 1, description = "R1", IsChecked = false });
lst.Add(new test1() { Id = 3, description = "R2", IsChecked = true });
lst.Add(new test1() { Id = 2, description = "R3", IsChecked = false });
lst.Add(new test1() { Id = 4, description = "R4", IsChecked = false });
repeater1.DataSource = lst;
repeater1.DataBind();
}
}
protected void rb1_CheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in repeater1.Items)
{
(item.FindControl("rb1") as RadioButton).Checked = false;
}
(sender as RadioButton).Checked = true;
}
After researching between SOF and a few forums I implemented a quite right solution using JS. I am handling another problem related with OnCheckedChanged´s event on RadioButton...
But the initial issue is fixed.
Forum Solution
I am posting the solution that works for me, using as base as a help coming from a forum, hoping it helps others as well with this bug.
REPEATER.
<asp:Repeater runat="server" ID="repeater1" OnItemDataBound="repeater1_ItemDataBound">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup" OnCheckedChanged="rb1_CheckedChanged"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
BACKEND
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rb1");
string script = "SetUniqueRadioButton('repeater1.*nameGroup',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}

Unable to change visibility of a div in asp.net C#

I have a div that displays loading symbol. I am setting visibility on change of a dropdown box. I want to set its visibility to false in C# after the SelectedIndexChanged method is complete.
Here is the div tag :
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage" >
<img class="loadingImg" src="../Images/ajax-loader.gif" />
</div>
Here is the jQuery function :
$(document).ready(function () {
//$('#loadingImage').hide();
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "block";
});
});
and this is how i am trying to set the visibility in C#
protected void selectSegment_SelectedIndexChanged(object sender, EventArgs e)
{
ckBLBusinessUnits.Visible = true;
loadingImage.Style["display"] = "none";
}
I tried various ways in C# like set visibility to false etc but nothing worked. Kindly help.
Change this:
loadingImage.Style["display"] = "none";
To this:
loadingImage.Style.Add("display", "none");
You can use hide and show methods to perform that action.
<div runat="server" clientidmode="Static" id="loadingImage" class="loadingImage">
<img class="loadingImg" src="loading.gif" />
</div>
<asp:DropDownList ID="selectSegment" ClientIDMode="Static"
runat="server">
<asp:ListItem Value="0">none</asp:ListItem>
<asp:ListItem Value="1">display</asp:ListItem>
</asp:DropDownList>
JS
$(document).ready(function () {
var modal = document.getElementById('loadingImage');
modal.style.display = "none";
$("#selectSegment").change(function () {
if (this.value === "1") {
$("#loadingImage").show();
} else {
$("#loadingImage").hide();
}
});
});
The div tag was outside of the updatepanel, moving the div inside of the updatepanel resolved the issue.

Badged list control for ASP.Net

Does any of you know of a lightweight list control for ASP.Net where I could add badged items on a horizontal line? Something like this:
You have to do like
function addMore()
{
$("div").append("<span>New Badge</span>");
}
span{
background-color:#7F7F7F;
padding:5px;
border-radius:10px;
margin:5px;
display:inline-block;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>jQuery</span>
<span>ajax</span>
<span>c#</span>
<span>Html</span>
<span>Java</span>
</div>
<input type="button" onclick="addMore();" value=" + ">
Use asp.net Literal control that will result you in span.
I used RadAutoCompleteBox which has the complete functions I needed.
Thanks Telerik.
http://docs.telerik.com/devtools/aspnet-ajax/controls/autocompletebox/overview
Edit: Added reference to Telerik for ASP.Net and sample code:
<telerik:RadAutoCompleteBox runat="server" ID="KeywordsAutoComplete"
Width="100%" OnLoad="KeywordsAutoComplete_Load" OnClientEntryAdding="restrictDuplicateEntry"
EmptyMessage="Type keywords..."
CssClass="autocompletebox control transition-025"
AllowCustomEntry="true" />
<script type="text/javascript">
// Restrict Duplicate Entry
function restrictDuplicateEntry(sender, eventArgs) {
var entries = sender.get_entries(),
count = entries.get_count();
for (var i = 0; i < count; i++) {
if (entries.getEntry(i).get_text() == eventArgs.get_entry().get_text())
{
eventArgs.set_cancel(true);
return;
}
}
}
</script>
C#:
protected void KeywordsAutoComplete_Load(object sender, EventArgs e)
{
DataTable dt; // Binding Data (For Lookup)
KeywordsAutoComplete.DataSource = dt;
KeywordsAutoComplete.DataBind();
}

JavaScript - Disabling Textbox upon Change of Drop Down List Index

I have the following code which suppoesedly disables or enables a textbox depending on the value in a drop down list.
Now this is how I am making a reference to this code from the drop down lists:
Unfortunately, the code is generating an exception. I believe that I am using the wrong event handler, that is, OnSelectedIndexChanged. How can I remedy the situation please?
1) replace OnSelectedIndexChanged with onchange
and
2) replace
var DropDown_Total = document.getElementById("DropDown_Total")
with
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
for all getElementById
3) replace (DropDown_Date.options[DropDown_Date.selectedIndex].value
with
(DropDown_Date.options[DropDown_Date.selectedIndex].text for both dropdown
try this it's working
<script type="text/javascript">
function DisableEnable() {
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
var Textbox_Total = document.getElementById("<%= Textbox_Total.ClientID %>")
var DropDown_Date = document.getElementById("<%= DropDown_Date.ClientID %>")
var Textbox_Date = document.getElementById("<%= Textbox_Date.ClientID %>")
if (DropDown_Total.options[DropDown_Total.selectedIndex].text == "Any Amount") {
Textbox_Total.disabled = true;
}
else {
Textbox_Total.disabled = false;
}
if (DropDown_Date.options[DropDown_Date.selectedIndex].text == "Any Date") {
Textbox_Date.disabled = true;
}
else {
Textbox_Date.disabled = false;
}
}
</script>
html
<asp:TextBox runat="server" ID="Textbox_Total" />
<asp:TextBox runat="server" ID="Textbox_Date" />
<asp:DropDownList ID="DropDown_Total" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Amount</asp:ListItem>
<asp:ListItem>Exact Amount</asp:ListItem>
<asp:ListItem>Below Amount</asp:ListItem>
<asp:ListItem>Above Amount</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDown_Date" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Date</asp:ListItem>
<asp:ListItem>Exact Date</asp:ListItem>
<asp:ListItem>Before</asp:ListItem>
<asp:ListItem>After</asp:ListItem>
</asp:DropDownList>
Use onchange event which will work for javascript function calling. OnSelectedIndexChanged is server side event.
just replace OnSelectedIndexChanged with onchange because onchange is handled by js. OnSelectedIndexChanged is handled by code behind.
Tutorial: how to disable/enable textbox using DropDownList in Javascript
In this function we pass dropdownlist id and textbox id as parameter in js function
<script type="text/javascript">
function DisableEnableTxtbox(DropDown, txtbox) {
if (DropDown.options[DropDown.selectedIndex].text == "free") {
txtbox.disabled = true;
}
else {
txtbox.disabled = false;
}
}
</script>
Now add the following code:
<td align="center" class="line">
<asp:DropDownList ID="ddl_MonP1" runat="server" CssClass="ppup2" onchange="DisableEnableTxtbox(this,txt_MonP1);"></asp:DropDownList>
<asp:TextBox ID="txt_MonP1" runat="server" CssClass="ppup" placeholder="Subject"></asp:TextBox>
</td>

Categories

Resources