asp:button onclick doesn't fire and page only refreshes - c#

Here's my aspx code for my button:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
And here's the function for the onclick event in a codebehind file:
public void Button1_Click(object sender, EventArgs e)
{
lblOutput.Text = txtFirstName.Text;
}
Alternatively, I've also used this in the onclick function, to see if the problem was the problem was the script in the function and not the button itself:
public void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("http://www.google.com");
}
Unfortunately this didn't work either. So the problem is probably something going wrong when the button is clicked, right?
The code behind is properly linked, because other functions in the page_load are working fine.
All that happens when my button is clicked is the page refreshes. To be honest I'm not sure if I could call it a refresh, the values in the from are still there, the page just jumps back to the top and nothing else happens.
I've also tried creating a second button, with a slightly different ID and onclick name, but the page still acts the same. I'm at a complete loss here. I haven't found anything on google that helps.
EDIT: Here's the full asp file. We're using ektron as a CMS so there's some weird code for that as well. And before anybody asks, yes it's in a form tag.
<%# Page Language="C#" MasterPageFile="~/InteriorPage.master" AutoEventWireup="true" CodeFile="urmintakeform.cs" Inherits="urmintakeform" Debug="true" %>
<%# Register Assembly="Ektron.Cms.Controls" Namespace="Ektron.Cms.Controls" TagPrefix="CMS" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<asp:Literal ID="Literal1" runat="server" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageBody" Runat="Server">
<div id="two-column-pagenav" class="section-divider-small">
<div class="column-one"><h2>University Relations and Marketing</h2></div>
<div class="column-two">
<p class="breadcrumb">
<CMS:FolderBreadcrumb ID="FolderBreadcrumb1" runat="server" DynamicParameter="id" SuppressWrapperTags="true" SuppressAddEdit="true" />
</p>
</div>
</div>
<div>
<img alt="URM Banner" src="/images/department_banners/urm-banner.jpg" />
<asp:Literal ID="litDeptImage" runat="server" />
</div>
<div id="" class="container section-divider-small">
<div class="column-one">
<div class="nav-aside widget">
<div class="opener-block">
<span>Menu</span>
<span class="title">University Relations and Marketing</span>
</div>
<div class="nav-page-box nav-slide">
<!--Replace this code with the Ektron Flex Menu Control-->
<CMS:FlexMenu ID="FlexMenu1" runat="server" SuppressAddEdit="true" DefaultMenuID="15032386736" DisplayXslt="xml/departments.xsl" SuppressWrapperTags="true" CacheInterval="0" AllowClose="true" EnableSmartOpen="True" AutoCollapseBranches="True" StartCollapsed="True" />
</div>
</div>
<div class="widget-holder">
<div class="dept-contact-box widget">
<h4>How to Reach Us</h4>
<p><span style="font-weight: bold">University Relations and Marketing</span><br />
xxxx<br />
xxxx<br />
xxxxx<br />
xxxx<a href="tel:xxxxxxxxxxxxxxxxxxxxxxx</a><br />
Email: xxxxxxxxxxxxxxxxxxx<br />
</p>
<div class="dept-social-media">
<a title="Twitter" href="xxxxxxxxxxxxxxx" target="_blank">
<img src="/images/socmed_icons/twitter-32x432.png" alt="Twitter" title="Twitter" />
</a>
</div>
</div>
</div>
</div>
<div id="body-content" class="column-two">
<div class="content-body">
<div id="ctl00_PageBody_ContentBlock1" class="content-container">
<div class="content-holder">
<asp:Literal ID="litInPageTopNav" runat="server" />
<asp:Literal ID="ltrContent" runat="server" />
<CMS:FormBlock ID="FormBlock1" runat="server" DynamicParameter="ekfrm" />
</div>
</div>
<div class="intake">
<h2>Tell us about yourself</h2>
<div class="userinfo">
<label id="firstname" runat="server" text="First Name:" >First Name:</label>
<asp:TextBox ID="txtFirstName" runat="server" MaxLength="50" placeholder="First Name"></asp:TextBox><p></p>
<label id="lblLastName" runat="server" text="">Last Name:</label>
<asp:TextBox ID="txtLastName" runat="server" MaxLength="50" placeholder="Last Name"></asp:TextBox><p></p>
<label id="lblDepartment" runat="server" text="">Department:</label>
<asp:TextBox ID="txtDepartment" runat="server" MaxLength="50" placeholder="Department"></asp:TextBox><p></p>
</div>
<!-- Phone and Email --------->
<div class="job">
<label id="lblPhone" runat="server" text="">Phone:</label>
<asp:TextBox ID="txtPhone" runat="server" MaxLength="50" placeholder="Phone"></asp:TextBox><p></p>
<label id="lblEmail" runat="server" text="Email">Email:</label>
<asp:TextBox ID="txtEmail" runat="server" MaxLength="50" placeholder="Email"></asp:TextBox><p></p>
</div>
<div style="clear:both;"></div>
<div class="help">
<h2>How can we help you?</h2>
<label id="lblCategory" runat="server" text="Help">Get Help With: </label>
<select name="areaselector" id="areaselector">
<option value="select">Select an Option</option>
<option value="design">Design</option>
<option value="imprinted">Imprinted</option>
<option value="photography">Photography</option>
<option value="social">Social Media</option>
<option value="written">Written Content</option>
</select>
<div id="design" class="areas" style="display:none" onchange="">
<asp:CheckBoxList ID="designASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="brochures">Brochures</asp:ListItem>
<asp:ListItem Value="posters">Posters</asp:ListItem>
<asp:ListItem Value="postcards">Postcards</asp:ListItem>
<asp:ListItem Value="booklets">Booklets</asp:ListItem>
<asp:ListItem Value="advertisement">Advertisement Design</asp:ListItem>
<asp:ListItem Value="digitalMarketing">Digital Marketing Material</asp:ListItem>
<asp:ListItem Value="other">Other Promotional Material</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="imprinted" class="areas" style="display:none">
<asp:CheckBoxList ID="imprintedASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="licensed vendors">Licensed Vendors</asp:ListItem>
<asp:ListItem Value="Imprinted product search/sample products">Imprinted product search/sample products</asp:ListItem>
<asp:ListItem Value="billboard leasing">Billboard Leasing</asp:ListItem>
<asp:ListItem Value="Imprinted product art/design">Imprinted product art/design</asp:ListItem>
<asp:ListItem Value="table covers">Table covers</asp:ListItem>
<asp:ListItem Value="retractable banners">Retractable banners</asp:ListItem>
<asp:ListItem Value="temporary signage">Temporary signage</asp:ListItem>
<asp:ListItem Value="tigerizing">"Tigerizing"</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="photography" class="areas" style="display:none">
<asp:CheckBoxList ID="photographyASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Official faculty and staff portraits">Official facutly and staff portraits</asp:ListItem>
<asp:ListItem Value="Groups and/or organizatoin portraits">Groups and/or organization Portraits</asp:ListItem>
<asp:ListItem Value="Organization Event photos">Organization Event photos</asp:ListItem>
<asp:ListItem Value="Student Event photos">Student Event photos</asp:ListItem>
<asp:ListItem Value="Departmental brochure and web photos">Departmental brochure and web photos</asp:ListItem>
<asp:ListItem Value="Sporting events">Sporting events</asp:ListItem>
<asp:ListItem Value="Guest speakers">Guest speakers</asp:ListItem>
<asp:ListItem Value="ID and/or nametags">ID and/or nametags</asp:ListItem>
<asp:ListItem Value="Visa\passports photographs">Visa\passports photographs</asp:ListItem>
<asp:ListItem Value="Scanning, retouching and custom printing">Scanning, retouching and custom printing</asp:ListItem>
<asp:ListItem Value="Archive/history FHSU image retrieval">Archive/history FHSU image retrieval</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="social" class="areas" style="display:none">
<asp:CheckBoxList ID="socialASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Training">Training</asp:ListItem>
<asp:ListItem Value="Event coverage">Event coverage</asp:ListItem>
<asp:ListItem Value="Marketing/promotion">Marketing/Promotion</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="written" class="areas" style="display:none">
<asp:CheckBoxList ID="writtenASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Print">Print</asp:ListItem>
<asp:ListItem Value="Web">Web</asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
<div class="tellusmore">
<h2>Tell us more about your request</h2>
<asp:TextBox ID="tellUsMoreBox" TextMode="MultiLine" runat="server" Columns="50" Rows="6" />
</div>
<!--<asp:Button ID="btnSubmit" runat="server" Text="Submit Application" Enabled="true" CssClass="submit" onclick="btnSubmit_Click" />
<asp:Button ID="asdf" runat="server" Text="Submit Application" Enabled="true" CssClass="submit" OnClick="btnSubmit_Click" />-->
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" CausesValidation="false"/>
</div>
</div>
</div>
</div>
</asp:Content>
Here's the C# file:
protected void Page_Load(object sender, EventArgs e)
{
ContentBlock ContentBlock1 = new ContentBlock();
ContentBlock1.SuppressWrapperTags = true;
ContentBlock1.DefaultContentID = 64;
ContentBlock1.DynamicParameter = "id";
ContentBlock1.Page = this.Page;
ContentBlock1.Fill();
//this.ltrContent.Text = ContentBlock1.Text.Replace("width", "max-width");
string lsContent = ContentBlock1.Text.Replace("width:", "max-width:");
lsContent = lsContent.Replace("width=", "max-width=");
//this.ltrContent.Text = lsContent;
//this.ContentBlock1.Text = lsContent;
FolderBreadcrumb1.Text += " > " + new CultureInfo("en").TextInfo.ToTitleCase(Server.HtmlDecode(ContentBlock1.EkItem.Title)) + "";
// dynamically generate an image if it been added as a meta image selector
Ektron.Cms.CustomAttributeList ContentMetaData;
ContentMetaData = ContentBlock1.GetMetaData();
if (ContentMetaData.GetItemByName("department-image").Value.ToString().Length > 0)
{
string extension;
extension = Path.GetExtension(Convert.ToString(ContentMetaData.GetItemByName("department-image").Value));
string ext = extension.Substring(0, 4);
if (ext == ".swf")
{
//is flash
litDeptImage.Text = "<object id=\"myId\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"730\" height=\"175\">";
litDeptImage.Text += " <param name=\"movie\" value=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" />";
litDeptImage.Text += " <!--[if !IE]>-->";
litDeptImage.Text += " <object type=\"application/x-shockwave-flash\" data=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" width=\"730\" height=\"175\">";
litDeptImage.Text += " <!--<![endif]-->";
litDeptImage.Text += " <div>";
litDeptImage.Text += " <p>You have javascript turned off or are not running the latest version of Adobe Flash Player. To best view this site, please <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" /></p>";
litDeptImage.Text += " </div>";
litDeptImage.Text += " <!--[if !IE]>-->";
litDeptImage.Text += " </object>";
litDeptImage.Text += " <!--<![endif]-->";
this.litDeptImage.Text += "</object>";
}
else
{
//else image
litDeptImage.Text = "<img class=\"ImageInline\" src=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" alt=\" \" />";
}
}
//grab collection id from the folder id that the content block belongs to
Ektron.Cms.API.Content.Content apiContent = new Ektron.Cms.API.Content.Content();
Ektron.Cms.Content.EkContent ekContent = apiContent.EkContentRef;
Microsoft.VisualBasic.Collection colldat = ekContent.GetAllCollectionsInfo(ContentBlock1.EkItem.FolderId, "id");
string collid = null;
foreach (Microsoft.VisualBasic.Collection field in colldat)
{
collid = field[1].ToString(); // collection id
}
long collint = Convert.ToInt64(collid);
//create the collection object we'll be using to get department nav pages
Ektron.Cms.Controls.Collection coll = new Collection();
coll.DefaultCollectionID = collint;
// set the standard coll properties
coll.DisplayXslt = "xml/departments-nav.xsl";
// attatch it to our invisible literal and fill it
coll.Page = Page;
coll.Fill();
if (!String.IsNullOrEmpty(collid))
litInPageTopNav.Text = coll.Text;
//Use the meta data we grabbed earlier to display title, keywords and description
Literal1.Text = "<title>" + Convert.ToString(ContentMetaData.GetItemByName("Title").Value) + " - xxxxxx University</title>\n";
Literal1.Text += "<meta name=\"keywords\" content=\"" + Convert.ToString(ContentMetaData.GetItemByName("Keywords").Value) + "\">\n";
Literal1.Text += "<meta name=\"description\" content=\"" + Convert.ToString(ContentMetaData.GetItemByName("Description").Value) + "\">\n";
//lblOutput.Text = Output;
}
public void Button1_Click(object sender, EventArgs e)
{
lblOutput.Text = txtFirstName.Text;
}
EDIT 2: Here's the tag that's on the page when viewing the pages source at run-time, provided by I believe possibly the master file. As I said earlier we use ektron cms. Could the form tag be a problem?
<form method="post" action="/urm/intake/" id="aspnetForm" onsubmit="if('undefined' == typeof Ektron || !Ektron.FormBlock || !typeof Ektron.FormBlock.validate || Ektron.FormBlock.validate(this)){$ektron('input[type=submit]').attr('disabled','disable');return true;}else{return false;}">

Figured it out. The CMS was the one at fault. I was viewing the page online with the URL given by the Ektron CMS. changing the formblock
<CMS:FormBlock ID="FormBlock1" runat="server" DynamicParameter="ekfrm" />
to a content block fixed it. The form block in ektron CMS caused problems.

Related

Retrieving CheckBoxList Values in Function

I have a cblSchedule checkboxlist in my .ascx page that allows selection of Daily/Weekly:
<div class="form-group" id="schedule">
<label class="control-label col-md-2" id="lblSchedule">Schedule</label>
<div class="col-md-3">
<div class="input-group">
<asp:CheckboxList ID="cblSchedule" ClientIDMode="Static" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleSchedule(this)" >
<asp:ListItem Text="Daily" Value="Daily"></asp:ListItem>
<asp:ListItem Text="Weekly" Value="Weekly"></asp:ListItem>
</asp:CheckboxList>
</div>
</div>
</div>
There is a chkSelectDay checkboxlist displayed when Weekly is checked:
<div class="form-group" id="divSelectDay" >
<label class="control-label col-md-2" id="lblSelectDay">Select Day of Week</label>
<div class="col-md-3">
<div class="input-group">
<asp:CheckBoxList ID="chkSelectDay" CssClass="chkLabel" ClientIDMode="Static" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table">
<asp:ListItem Value="Monday">Mon</asp:ListItem>
<asp:ListItem Value="Tuesday">Tue</asp:ListItem>
<asp:ListItem Value="Wednesday">Wed</asp:ListItem>
<asp:ListItem Value="Thursday">Thu</asp:ListItem>
<asp:ListItem Value="Friday">Fri</asp:ListItem>
<asp:ListItem Value="Saturday">Sat</asp:ListItem>
<asp:ListItem Value="Sunday">Sun</asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
</div>
I have a toggle function that display/hide chkSelectDay when Weekly is checked/unchecked in cblSchedule :
function ToggleSchedule(controlId) {
var frmControl = document.getElementById(controlId.id);
var divDay = document.getElementById("divSelectDay");
var checkbox = frmControl.getElementsByTagName("input");
var counter = 0;
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked)
{
if (checkbox[i].value == "Weekly")
divDay.style.display = 'block';
}
else
{
if (checkbox[i].value == "Weekly") {
divDay.style.display = 'none';
//UNCHECK ALL chkSelectDay checkboxes <--
}
}
}
}
I would like to add in the functionality of unchecking all checkboxes in chkSelectDay when Weekly is unchecked in cblSchedule.
I tried to retrieve checkbox count via $('#chkSelectDay').
But I was unable to use .Count nor .Length, so I can't use a for-loop to set .Checked = false.
Thank you
First thing you should know is by default CheckBoxList stores its value inside ViewState and not show it in client-side. You need to add ClientValue attribute inside ListItem to let checkboxlist values available in client-side:
<asp:CheckboxList ID="cblSchedule" ClientIDMode="Static" CssClass="chkLabel" runat="server" AutoPostBack="false" CellPadding="5" CellSpacing="5" RepeatDirection="Horizontal" RepeatLayout="Table" onchange="ToggleSchedule(this)" >
<asp:ListItem Text="Daily" Value="Daily" ClientValue="Daily"></asp:ListItem>
<asp:ListItem Text="Weekly" Value="Weekly" ClientValue="Weekly"></asp:ListItem>
</asp:CheckboxList>
Then, handle change event to make sure that the Weekly value is passed, otherwise uncheck all of chkSelectDay checkboxes:
$("#cblSchedule input[type=checkbox]").change(function () {
var value = $(this).parent().attr('clientvalue');
// check if the value is 'weekly'
if (this.checked && value != "Weekly") {
// set all day selection checkboxes to 'unchecked'
$("[id*=chkSelectDay] input").removeAttr("checked");
// hide day selection checkboxes
$('#divSelectDay').css('display', 'none');
}
else {
// do something else
}
});
Related issues:
Get the Checkboxlist value when unchecked Client-Side
Check uncheck all CheckBoxes on the basis of another CheckBox
ASP.Net CheckBoxList: Check or uncheck all checkboxes client side using jQuery

Issue grabbing correct control/update panel in repeater

I'm having issues with dynamically updating a drop down list control when it is inside a repeater.
Basically I have a repeater and inside that repeater are 2 drop down lists. The one list is defined in my aspx page, the other drop down list is inside an update panel where I want to be able to have it dynamically update based on the selection of the first drop down list. I think part of my problem is the updatepanel is getting confused because I have more than one repeater item?
Here is the code for my repeater:
<asp:Repeater ID="billingTemplate" runat="server" OnItemDataBound="template_ItemDataBound">
<ItemTemplate>
<tr style="font-size: 100%" runat="server">
<td colspan="4" style="width: 100%; vertical-align: top">
<div class="panel panel-default panel-billing">
<asp:Panel CssClass="row panel-heading panel-heading-billing text-left" ID="headingBilling" ClientIDMode="Static" runat="server">
<div class="col-xs-1">
<input type="hidden" id="templateUK" runat="server" value='<%#Eval("templateUK")%>' />
</div>
<div class="col-sm-3">
<label for="ddlInvFilterType" class="col-sm-4 control-label text-right labelCls testclass">Filter Type:</label>
<div class="col-sm-8">
<asp:DropDownList runat="server" ID="ddlInvFilterType" ClientIDMode="Static" placeholder="Choose Filter Type" CssClass="form-control smallSize FilterType" AutoPostBack="true" OnSelectedIndexChanged="ddlFilterType_SelectedIndexChanged">
<asp:ListItem Value="">- None -</asp:ListItem>
<asp:ListItem Value="RevType1">Revenue Type 1</asp:ListItem>
<asp:ListItem Value="RevType2">Revenue Type 2</asp:ListItem>
<asp:ListItem Value="RevType3">Revenue Type 3</asp:ListItem>
<asp:ListItem Value="ServiceTeams">Service Team</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<asp:UpdatePanel ID="InvFilterValuePanel" ClientIDMode="Static" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<div class="col-sm-3">
<label for="ddlInvFilterValue" class="col-sm-4 control-label text-right labelCls">Filter Value:</label>
<div class="col-sm-8">
<asp:DropDownList runat="server" ID="ddlInvFilterValue" ClientIDMode="Static" placeholder="Choose Filter Value" CssClass="col-sm-6 form-control smallSize">
<asp:ListItem Value="">- None -</asp:ListItem>
</asp:DropDownList>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlInvFilterType" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
<asp:Panel CssClass="panel-collapse collapse" ID="collapseBilling" ClientIDMode="Static" runat="server">
<div class="panel-body">
<table class="table table-condensed table-bordered" style="margin: 0; padding: 0; border-top: none; border-bottom: none; border-left: thin; border-right: thin">
<tbody>
<%-- other controls --%>
</tbody>
</table>
</div>
</asp:Panel>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
Heres the code for my selected index change:
protected void ddlFilterType_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList ddl = (DropDownList)sender;
string ddlClass = ddl.CssClass;
string[] classes = ddlClass.Split(' ');
string repeaterClass = classes[classes.Length - 1];
string repeaterID = "0";
string appendStr = "";
if (repeaterClass.Contains("templateID"))
{
repeaterID = repeaterClass.Substring(repeaterClass.Length - 1);
appendStr = "_" + repeaterID;
}
foreach (RepeaterItem item in billingTemplate.Items)
{
HtmlInputHidden hidden = item.FindControl("headingBilling").FindControl("templateUK") as HtmlInputHidden;
if (hidden.Value == repeaterID)
{
DropDownList d1 = item.FindControl("headingBilling").FindControl("ddlInvFilterType") as DropDownList;
DropDownList d2 = item.FindControl("headingBilling").FindControl("ddlInvFilterValue") as DropDownList;
if (d1.SelectedValue.Length > 0)
{
d2.Items.Clear();
d2.Items.Add(new ListItem(" - None - ", ""));
switch (d1.SelectedValue)
{
case "ServiceTeams":
foreach (var pair in serviceTeamsController.GetAllServiceTeamsLOVs())
{
if (!String.IsNullOrWhiteSpace(pair.Value))
d2.Items.Add(new ListItem(pair.Value, pair.Key));
}
break;
default:
foreach (var pair in masterController.GetMasterLOVs(filterTypeDict[d1.SelectedValue]))
{
if (!String.IsNullOrWhiteSpace(pair.Value))
{
d2.Items.Add(new ListItem(pair.Value, pair.Key));
}
}
break;
}
}
else
{
d2.Items.Clear();
d2.Items.Add(new ListItem(" - None - ", ""));
}
}
}
}
catch (Exception ex)
{
}
}
Heres a screenshot of what I'm looking at when theres more than one repeater item:
Basically whats happening now is if I update the filter type in item2 it will update the filter value in item 1. If I update the filter type in item1 it will update the filter value in item 1 as expected.
What I want is to be able to update item2 filter type and then the filter value in item 2 is updated accordingly.
Anyone have any ideas on what I could be missing?
So ended up getting this to work, I think the main issue was the clientidmode was confusing the update panel somehow, so I removed that and made the update panel go around both drop downs. I also didnt end up needing the trigger so I removed that as well.

ASP.Net WebForm RadioButtonList doesn't postback selected correctly

The RadioButtonList is as the follows with no auto postback. My problem is when I select option 1 (value 1) and click either link button, the variable NotifyMe in the code behind is always true because the selected item is always on the default. I tried to set the EnableViewState just for this RadioButtonList and leave the reset of the form without ViewState. It didn't work either. Thank you for your help.
<div id="preferencePopup" style="display: none" title="Set Preference">
Select an option than click either of the button below.
<div>
<ul id="preferenceOptions">
<li>
<asp:RadioButtonList ID="PreferenceNotification" runat="server" CssClass="radioButtonNoBorder">
<asp:ListItem Text="No notification" Value="1" />
<asp:ListItem Text="Notification" Value="2" selected="true" />
</asp:RadioButtonList>
</li>
</ul>
</div>
<div class="col-md-offset-1 col-md-11 col-sm-12 text-center">
<asp:LinkButton ID="btnSavePreference" runat="server" OnClick="btnSavePreference_Click" CssClass="btn btn-default">Clear & Save</asp:LinkButton>
<asp:LinkButton ID="btnAddAndSave" runat="server" OnClick="btnSavePreference_Click" CssClass="btn btn-default">Add & Save</asp:LinkButton>
</div>
</div>
protected void btnSavePreference_Click(object sender, EventArgs e) {
bool NotifyMe = PreferenceNotification.SelectedItem.Value == "2" ? true : false;
}

Validation with one radio button option only

I have a radiobuttonlist with three choices. When a user clicks on the "Provided" option, two textboxes open underneath it. These two are required when selecting that option. How can I require these two only when that option is marked but not if it isn't and still allow me to process the form? I tried using ValidationGroup, but since I am still new to developing, I think I am missing something. Any guidance would be appreciated, thanks in advance!
<asp:RadioButtonList ID="rblCreat" runat="server" RepeatDirection="Horizontal" CssClass="rblMargin rblCreat">
<asp:ListItem>N/A</asp:ListItem>
<asp:ListItem>DIC to Obtain</asp:ListItem>
<asp:ListItem>Provided</asp:ListItem>
</asp:RadioButtonList>
<div style="display: none;" id="provided-fields">
<br />
<p style="margin-left: 250px">
Results:
<asp:TextBox ID="txtCreatResults" runat="server" Width="99px" TabIndex="21" Height="22px"
CssClass="margin"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvResults" runat="server" ControlToValidate="txtCreatResults"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
<br />
Date:
<asp:TextBox ID="txtCreatDate" runat="server" Width="99px" TabIndex="22" onkeydown="return DateFormat(this, event.keyCode)"
Height="22px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDate" runat="server" ControlToValidate="txtCreatDate"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
</p>
</div>
Your code Behind
protected void Page_Load(object sender, EventArgs e)
{
rblCreat.Items[0].Attributes.Add("onclick", "abc('1');");
rblCreat.Items[1].Attributes.Add("onclick", "abc('2');");
rblCreat.Items[2].Attributes.Add("onclick", "abc('3');");
}
Your Java Script
<script language="javascript" type="text/javascript">
function abc(ID) {
if (ID == '3') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "provided", "", false, false));
}
document.getElementById('providedfields').style.display = 'block';
}
if (ID == '1' || ID == '2') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "newValGroup", "", false, false));
}
document.getElementById('providedfields').style.display = 'none';
}
}
</script>
Your HTML
<asp:radiobuttonlist id="rblCreat" runat="server" repeatdirection="Horizontal" cssclass="rblMargin rblCreat">
<asp:ListItem Value="1">N/A</asp:ListItem>
<asp:ListItem Value="2">DIC to Obtain</asp:ListItem>
<asp:ListItem Value="3">Provided</asp:ListItem>
</asp:radiobuttonlist>
<div style="display: none;" id="providedfields">
<br />
<p style="margin-left: 250px">
Results:
<asp:textbox id="txtCreatResults" runat="server" width="99px" tabindex="21" height="22px"
cssclass="margin"></asp:textbox>
<asp:requiredfieldvalidator id="rfvResults" runat="server" controltovalidate="txtCreatResults"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
<br />
Date:
<asp:textbox id="txtCreatDate" runat="server" width="99px" tabindex="22" height="22px"></asp:textbox>
<asp:requiredfieldvalidator id="rfvDate" runat="server" controltovalidate="txtCreatDate"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
</p>
</div>
<asp:button id="btn" validationgroup="provided" runat="server" />
When you click on the button it will postback in case of other then provided options.
I believe a CustomValidator could help you with this.
<asp:CustomValidator
runat="server"
id="cusCustom"
controltovalidate="txtCreatDate"
onservervalidate="cusCustom_ServerValidate"
errormessage="You must enter a text." />
and then write the method in your code behind with whatever logic you might need.
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (rblCreat.SelectedIndex == 1)
{
if (e.Value.Length > 0)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}
else {
e.IsValid = true;
}
}
Note: This is not written in any IDE so I can't be sure about the syntax.
Before processing the form, you could check (from the server code) whether the required option in the radiobuttonlist is checked. If not, set the Enabled property of the requiredfieldvalidators to False.

UpdatePanel, ModalPopupExtender, and enter keypress issues

Have an UpdatePanel that contains 2 panels with default buttons set to listen to enter key presses. That UpdatePanel is the PopupControl for a ModalPopupExtender.
Running into an issue when pressing enter in the modal popup in which the entire page posts back. Any ideas? Here are some code snippets (I've removed the extraneous fields...):
<div runat="server" id="divShippingEstimatorPopup" class="shippingEstimatorModalPopup">
<asp:UpdatePanel ID="upPopup" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="pnlShippingEstimator" DefaultButton="lnkbtnGetEstimates">
<div class="title content_title">Shipping Estimator</div>
<asp:Label runat="server" ID="lblMessage" />
<table cellpadding="0" cellpadding="0" class="shipping">
<!-- Removed to shorten code snippet -->
<tr>
<td colspan="2">
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnGetEstimates" CssClass="button_action button_margin_right" CausesValidation="false">Get Estimates</Monarch:LinkButtonDefault>
<asp:LinkButton runat="server" ID="lnkbtnCancel" CssClass="button_secondary button_secondary_fixed" CausesValidation="false">Cancel</asp:LinkButton>
<div class="clear"></div>
</div>
<div class="clear"></div>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlShippingOptions" DefaultButton="lnkbtnSetEstimate">
<div class="shippingOptionsHolder" runat="server" id="divShippingOptionsHolder">
<!-- Removed to shorten code snippet -->
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnSetEstimate" CssClass="button_action">Set Estimate</Monarch:LinkButtonDefault>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Keep in mind the LinkButtonDefault is just this:
public class LinkButtonDefault : LinkButton
{
private const string AddClickScript = "SparkPlugs.FixLinkButton('{0}');";
protected override void OnLoad(EventArgs e)
{
string script = String.Format(AddClickScript, ClientID);
Page.ClientScript.RegisterStartupScript(GetType(), "click_" + ClientID,
script, true);
base.OnLoad(e);
}
}
Finally, here is the rest of the control:
<asp:UpdatePanel runat="server" ID="upGetEstimate">
<ContentTemplate>
<asp:LinkButton runat="server" ID="lnkbtnGetEstimate" CausesValidation="false">Get Estimate</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
<ajaxToolKit:ModalPopupExtender ID="shippingEstimatorPopupExtender" runat="server" TargetControlID="lnkbtnFake" PopupControlID="divShippingEstimatorPopup" BackgroundCssClass="monarchModalBackground"></ajaxToolKit:ModalPopupExtender>
<asp:LinkButton runat="server" ID="lnkbtnFake" style="display:none;"/>
<Monarch:PopupProgress ID="popupProgressGetEstimate" runat="server" AssociatedUpdatePanelId="upGetEstimate" />
<Monarch:PopupProgress ID="popupProgressGetEstimates" runat="server" AssociatedUpdatePanelId="upPopup" />
Basically, the user clicks Get Estimate, a progress bar appears while it loads the form, the form shows in a modal popup. I'm guessing this is something simple, but I can't just get the right combination to get this working properly.
First of all try what happens if you use your scriptmanager to register script in the code behind.
I use this method for registering scripts:
public static void RegisterStartupScript(Control c, string script)
{
if ((ToolkitScriptManager.GetCurrent(c.Page) as ToolkitScriptManager).IsInAsyncPostBack)
ToolkitScriptManager.RegisterStartupScript(c, c.GetType(), "Script_" + c.ClientID.ToString(), script, true);
else
c.Page.ClientScript.RegisterStartupScript(c.GetType(), c.ClientID, script, true);
}
This checks if you have ScriptManager in your page. If it doesn't, it uses the full postback version.

Categories

Resources