AJAX Calendar Extender / Textbox values always null after postback - asp.net

Im sure this is a very simple and easy to answer question but I've been looking at this too long and being new to ASP I cant seem to find a solution that works.
I have an ASP calendar extender, I click it and the calendar displays as expected, the selected date appears in the textbox, but when the page then posts back I cant get the selected date value from either the textbox.text or the calendarextender.selecteddate properties, I tested this by trying to assign these values to a string variable in the page_load event.
Am I missing something here?
Here is my code so far:
I have the script manager declared at the start of my form
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
Then my textbox / datepicker within table lower down
<asp:TextBox ID="DateChooser"
runat="server"
ReadOnly="true"
style="text-align: center" Width="85px"
OnTextChanged="DateChooser_TextChanged"
AutoPostBack="true" />
<div style='position:relative; z-index:1'>
<cc1:CalendarExtender CssClass="cal_Theme1"
ID="DateChooser_CalendarExtender"
runat="server"
Enabled="True"
TargetControlID="DateChooser"
PopupPosition="Right"
Format="dd MMM yyyy"
/>
</div>
</td>

Since you have set textbox ReadOnly to true it lose changes performed by client-side code on postback. Follow this link for more detailed explanation: TextBox.ReadOnly Property Consider to set readonly attribute on textbox by client code.

Related

TextBox loses value after post back with TextMode Number

Got weird problem. I have simple page with TextBox:
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TextBox ID="amountTextBox" runat="server" TextMode="Number" />
<asp:Button runat="server" Text="Confirm" OnClick="confirmButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
After Button click I try to get TextBox value:
public partial class test : Page {
protected void confirmButton_Click(object sender, EventArgs e) {
var answer = amountTextBox.Text;
}
}
but it's empty. If I remove UpdatePanel, I manage to get the value. If I leave UpdatePanel and remove TextMode property, I manage to get the value. But why can't I have TextBoxt with TextMode set to Number in UpdatePanel?
It is a known issue, a fix is available in .NET 4.5 RTM.
Description
HTML5 has new types for the input tag, such as type="number", which is
needed to make mobile phones display a numerical keyboard instead of a
text keyboard. When doing a full postback of the page it works in all
browsers. But if I puts these in an updatepanel on a website to do a
partical postback, then none of the new HTML input types are included
in the postback response to the server from those browsers that
understands these new types (Safari/WebKit and Opera). It works
correctly in IE8 and Firefox 4, but probably only because they have
not implemented these new types and falls back to understanding it as
a type="text" field.
Here is another question with this issue and workarounds: UpdatePanel with input type other than text in html5.

Textbox not retaining its value after postback using a calendar extender

I'm using CalendarExtender with a textbox as the target control. My code is below:
<asp:TextBox ID="textBoxFromDate" runat="server" EnableViewState="true" />
<asp:CalendarExtender ID="textBoxFromDate_CalendarExtender" runat="server" Enabled="True"
TargetControlID="textBoxFromDate" Format="dd/MM/yyyy" EnableViewState="true">
</asp:CalendarExtender>
So I use the calendar control to set the value within the textbox. This works fine, however when a postback happens on the page the textbox value is reset to the default date for the calendar control.
How can I get the textbox to retain its value on a postback?
Thanks in advance.
I'm using ASP.Net 4.0.
did you try setting readonly field dynamically rather than in markup ? Also i'd make sure you are not resetting the value in Page_Load() during postbacks.
Or what about trying somehting like this on Page_load , also checking to see if there is a valid date in box before attempting to set it to the calendar extender selected date ?
if (IsPostBack)
{
MyCalendarExtender.SelectedDate =
DateTime.ParseExact(MyTextBox.Text, MyCalendarExtender.Format, null);
}

Stop Postback in Image Button after validation failed

I have a aspx page containing a text box and an image button for search. I have used compare validator (to check for integer values) with the textbox. But the page reloads on the image button click even if I enter alphanumeric characters, along with showing the error message.
I tried using a regularexpressionvalidator instead but the problem persists.
But when i used a simple asp:button instead and binded it with textbox validation, its working fine (i.e. postback does not occur on incorrect value of textbox) and same is true with dropdownlist also (no postback occuring).
Please suggest.
Here's the code-
#peroija : Here's the code
<asp:ImageButton ID="btnSearch" runat="server" OnClick="btnSearch_Click"
ToolTip="Search" ValidationGroup="valControl" CausesValidation="true" />
<asp:TextBox ID="txtWidth" CssClass="TextFont" runat="server"
Width="233px" MaxLength="20"
ValidationGroup="valControl" CausesValidation="true"></asp:TextBox>
<asp:CompareValidator runat="server" ID="cmpValWidth"
ErrorMessage="Please enter integer values" ControlToValidate="txtWidth" Display="Dynamic"
Operator="DataTypeCheck" ValidationGroup="valControl"Type="Integer"/>
Sounds to me like you need to write
if(!isPostBack)
{
"your code"
}
in the code behind. To prevent the code from being run if the page is not viewed for the first time
Remove this from your textbox, you only need it on the validator and the button:
ValidationGroup="valControl" CausesValidation="true"
If javascript is disabled, then there will be no client side validation, so always check the validity on the server side also:
if(Page.IsValid)
{
"your btnSearch_Click code"
}

Server Control Auto Postback with form has _blank attribute

My case is I have an asp.net page has a form
<form id="form1" runat="server" target="_blank">
and a button redirect to another page and this page will open in a new window because of the target attribute of the form .
<asp:Button ID="button1" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
and I have a dropdownlist has auto postback = true to post the past to fill another dropdownlist by selected data .
<asp:dropdownliast id="Make" name="Make" runat="server" autopostback="true"></asp:dropdownlist>
the question is : why when I select item from the auto postbacked dropdown an blank page opened ?
I need a way to post the page by the dropdownlist without openning a blank page ..
Thank you,
For lack of a better idea, you could just remove the target="_blank" attribute from your markup, and when your button is clicked, modify the form tag with JavaScript and set the attribute.
You can set the OnClientClick property and run JavaScript when it's clicked. For example:
<asp:Button ID="button1" OnClientClick="document.getElementById('form1').setAttribute('target', '_blank')" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
You could always just adjust your buttonpress code to open a new window such as this:
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('kindofpage.aspx', 'kindofpage');" />
then remove the:
target="_blank"
From the form tag.
I struggled with a similar situation but solved it in the following way.
As mentioned in this answer, you can use the OnClientClick property to set the target to "_blank". E.g.
<asp:Button ID="button1" OnClick="codebehind_method" OnClientClick="document.forms[0].target = '_blank';" runat="server" Text="targets new window" />
Then, in the aspx page that my "codebehind_method" function redirects to, I reset the target of the opener form like so:
<script type="text/javascript">
function resetTarget() {
opener.document.forms[0].target = '';
}
</script>
<body onload="resetTarget()">
Now, if you go back to your opener form and use a control that does not have the "OnClientClick" property set, the AutoPostBack should occur in the same tab.
If you want to find your form by ID, replace "document.forms[0]" with:
document.getElementByID('yourFormName')
<form id="form1" runat="server">

how to disable previous dates in CalendarExtender control through its render event?

Basically, I just want allow select dates greater than today. I'd prefer this way to avoid show alert messages.
I don't think that it is supported in the current version of the Toolkit to restrict selectable dates. This is a simple workaround handling the ClientDateSelectedChanged-Event and validate the selected date:
How to make sure user does not select a date earlier than today or greater than today
There could be instances where you do not want the user to select a day earlier than the current date. For example: when you are providing the user a form to book tickets, you would not like him to choose an earlier date. To achieve this requirement, use the following javascript code.
Prevent the User from selecting a Date Earlier than today
<head runat="server">
<title>Calendar Extender</title>
<script type="text/javascript">
function checkDate(sender,args)
{
if (sender._selectedDate < new Date())
{
alert("You cannot select a day earlier than today!");
sender._selectedDate = new Date();
// set the date back to the current date
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}
</script>
</head>
Call the code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1"
runat="server" OnClientDateSelectionChanged="checkDate" TargetControlID="TextBox1" />
</div>
</form>
Select Date Greater than today
In the javascript, just change this line
sender._selectedDate > new Date()
Note: You may argue that the user can still change the date by typing into the textbox or entering an invalid date. Well that can be easily handled using a ValidationControl and is covered in the next tip.
Add validation to the CalendarExtender Control
A simple way to add validation to the Calendar is to add a ValidationControl to the textbox associated with a CalendarExtender. You have two choices:
Add an Extender to the ValidationControl. To do so, drag and drop a ValidationControl > click on the smart tag of the ValidationControl > choose Add Extender. From the Extender Wizard, choose ValidatorCalloutExtender. Using this approach makes it extremely easy to discover and attach control extenders to your controls. In VS 2005, you had to do this process manually, by wiring up control extenders.
You can choose not to add the Extender.
We will go ahead with option A. We will be adding two ValidationControls to the TextBox. The first, a CompareValidator to check if the user does not enter an invalid date (Eg: May 32) and second, a RangeValidator to keep the date range as desired.
Adding CompareValidator
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Invalid Date"
Operator="DataTypeCheck" Type="Date">
</asp:CompareValidator>
<cc1:ValidatorCalloutExtender ID="CompareValidator1_ValidatorCalloutExtender"
runat="server" Enabled="True" TargetControlID="CompareValidator1">
</cc1:ValidatorCalloutExtender>
Adding RangeValidator – We will restrict the user to select a date range starting from today to 15 days from now.
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RangeValidator"
Type="Date">
</asp:RangeValidator>
<cc1:ValidatorCalloutExtender ID="RangeValidator1_ValidatorCalloutExtender"
runat="server" Enabled="True" TargetControlID="RangeValidator1">
</cc1:ValidatorCalloutExtender>
In the code behind of your page, add this code
C#
protected void Page_Load(object sender, EventArgs e)
{
RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString();
RangeValidator1.MaximumValue = System.DateTime.Now.AddDays(15).ToShortDateString();
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString()
RangeValidator1.MaximumValue = System.DateTime.Now.AddDays(15).ToShortDateString()
End Sub
Well those were some tips associated with the CalendarExtender. As future versions of the toolkit are released, we should be hopeful that there will exist easier ways, of achieving this functionality.
From: http://www.dotnetcurry.com/ShowArticle.aspx?ID=149
Another advanced approach would be to extend the CalendarExtender javascript, but then you have your own custom version of the ajax toolkit.
http://codegoeshere.blogspot.com/2007/06/extending-calendarextender.html
set StartDate property of the calender extender to DateTime.Now.Date in the page load
this will show the previous dates as unselectable

Resources