I have an ASP.NET FormView within an updatepanel. I'm auto-saving the form by setting AutoPostBack=true for each of the items within the FormView.
This means the user can click a few elements in quick succession and fire off a few async postbacks almost simultaneously.
The issue I have is that the user is able to keep scrolling down the form while the async postbacks are not yet complete. The browser always scrolls back to the position it was in at the first postback.
Page.MaintainScrollPositionOnPostback is set to False.
I've tried all sorts of things in ajax and jquery with:
pageLoad
add_initializeRequest
add_endRequest
document.ready
etc..
but I always only seem to be able to access the scroll Y as it was on the first postback.
Is there any way to retrieve the current scroll Y when the postback completes, so I can stop the scrolling occurring? Or perhaps is it possible to disable the scrolling behaviour?
Thanks!
Update
Thanks to #chprpipr, I was able to get this to work. Here's my abbreviated solution:
var FormScrollerProto = function () {
var Me = this;
this.lastScrollPos = 0;
var myLogger;
this.Setup = function (logger) {
myLogger = logger;
// Bind a function to the window
$(window).bind("scroll", function () {
// Record the scroll position
Me.lastScrollPos = Me.GetScrollTop();
myLogger.Log("last: " + Me.lastScrollPos);
});
}
this.ScrollForm = function () {
// Apply the last scroll position
$(window).scrollTop(Me.lastScrollPos);
}
// Call this in pageRequestManager.EndRequest
this.EndRequestHandler = function (args) {
myLogger.Log(args.get_error());
if (args.get_error() == undefined) {
Me.ScrollForm();
}
}
this.GetScrollTop = function () {
return Me.FilterResults(
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
);
}
this.FilterResults = function (n_win, n_docel, n_body) {
var n_result = n_win ? n_win : 0;
if (n_docel && (!n_result || (n_result > n_docel)))
n_result = n_docel;
return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
}
Main page:
...snip...
var logger;
var FormScroller;
// Hook up Application event handlers.
var app = Sys.Application;
// app.add_load(ApplicationLoad); - use pageLoad instead
app.add_init(ApplicationInit);
// app.add_disposing(ApplicationDisposing);
// app.add_unload(ApplicationUnload);
// Application event handlers for component developers.
function ApplicationInit(sender) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack()) {
prm.add_initializeRequest(InitializeRequest);
prm.add_beginRequest(BeginRequest);
prm.add_pageLoading(PageLoading);
prm.add_pageLoaded(PageLoaded);
prm.add_endRequest(EndRequest);
}
// Set up components
logger = new LoggerProto();
logger.Init(true);
logger.Log("APP:: Application init.");
FormScroller = new FormScrollerProto();
}
function InitializeRequest(sender, args) {
logger.Log("PRM:: Initializing async request.");
FormScroller.Setup(logger);
}
...snip...
function EndRequest(sender, args) {
logger.Log("PRM:: End of async request.");
maintainScroll(sender, args);
// Display any errors
processErrors(args);
}
...snip...
function maintainScroll(sender, args) {
logger.Log("maintain: " + winScrollTop);
FormScroller.EndRequestHandler(args);
}
I also tried calling the EndRequestHandler (had to remove the args.error check) to see if it reduced flicker when scrolling but it doesn't. It's worth noting that the perfect solution would be to stop the browser trying to scroll at all - right now there is a momentary jitter which would not be acceptable in apps with a large user base.
(The scroll top code is not mine - found it on the web.)
(Here's a helpful MSDN page for the clientside lifecycle: http://msdn.microsoft.com/en-us/library/bb386417.aspx)
Update 7 March:
I just found an extremely simple way to do this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beginRequest);
function beginRequest()
{
prm._scrollPosition = null;
}
</script>
You could bind a function that logs the current scroll position and then reapplies it after each endRequest. It might go something like this:
// Wrap everything up for tidiness' sake
var FormHandlerProto = function() {
var Me = this;
this.lastScrollPos = 0;
this.SetupForm = function() {
// Bind a function to the form's scroll container
$("#ContainerId").bind("scroll", function() {
// Record the scroll position
Me.lastScrollPos = $(this).scrollTop();
});
}
this.ScrollForm = function() {
// Apply the last scroll position
$("#ContainerId").scrollTop(Me.lastScrollPos);
}
this.EndRequestHandler = function(sender, args) {
if (args.get_error() != undefined)
Me.ScrollForm();
}
}
}
var FormHandler = new FormHandlerProto();
FormHandler.Setup(); // This assumes your scroll container doesn't get updated on postback. If it does, you'll want to call it in the EndRequestHandler.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(FormHandler.EndRequestHandler);
Simply put the Timer control within the content template.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:ImageButton ID="ImageButton1" runat="server" Height="350" Width="700" />
</ContentTemplate>
</asp:UpdatePanel>
I'm trying to use asp:
<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>
I want a way to specify the maxlength property, but apparently there's no way possible for a multiline textbox. I've been trying to use some JavaScript for the onkeypress event:
onkeypress="return textboxMultilineMaxNumber(this,maxlength)"
function textboxMultilineMaxNumber(txt, maxLen) {
try {
if (txt.value.length > (maxLen - 1)) return false;
} catch (e) { }
return true;
}
While working fine the problem with this JavaScript function is that after writing characters it doesn't allow you to delete and substitute any of them, that behavior is not desired.
Have you got any idea what could I possibly change in the above code to avoid that or any other ways to get round it?
Use a regular expression validator instead. This will work on the client side using JavaScript, but also when JavaScript is disabled (as the length check will be performed on the server as well).
The following example checks that the entered value is between 0 and 100 characters long:
<asp:RegularExpressionValidator runat="server" ID="valInput"
ControlToValidate="txtInput"
ValidationExpression="^[\s\S]{0,100}$"
ErrorMessage="Please enter a maximum of 100 characters"
Display="Dynamic">*</asp:RegularExpressionValidator>
There are of course more complex regexs you can use to better suit your purposes.
try this javascript:
function checkTextAreaMaxLength(textBox,e, length)
{
var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;
var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
Roll your own:
function Count(text)
{
//asp.net textarea maxlength doesnt work; do it by hand
var maxlength = 2000; //set your value here (or add a parm and pass it in)
var object = document.getElementById(text.id) //get your object
if (object.value.length > maxlength)
{
object.focus(); //set focus to prevent jumping
object.value = text.value.substring(0, maxlength); //truncate the value
object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
return false;
}
return true;
}
Call like this:
<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>
Things have changed in HTML5:
ASPX:
<asp:TextBox ID="txtBox" runat="server" maxlength="2000" TextMode="MultiLine"></asp:TextBox>
C#:
if (!IsPostBack)
{
txtBox.Attributes.Add("maxlength", txtBox.MaxLength.ToString());
}
Rendered HTML:
<textarea name="ctl00$DemoContentPlaceHolder$txtBox" id="txtBox" maxlength="2000"></textarea>
The metadata for Attributes:
Summary: Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
Returns: A System.Web.UI.AttributeCollection of name and value pairs.
use custom attribute maxsize="100"
<asp:TextBox ID="txtAddress" runat="server" maxsize="100"
Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
<script>
$("textarea[maxsize]").each(function () {
$(this).attr('maxlength', $(this).attr('maxsize'));
$(this).removeAttr('maxsize');
});
</script>
this will render like this
<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>
Another way of fixing this for those browsers (Firefox, Chrome, Safari) that support maxlength on textareas (HTML5) without javascript is to derive a subclass of the System.Web.UI.WebControls.TextBox class and override the Render method. Then in the overridden method add the maxlength attribute before rendering as normal.
protected override void Render(HtmlTextWriter writer)
{
if (this.TextMode == TextBoxMode.MultiLine
&& this.MaxLength > 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
}
base.Render(writer);
}
$('#txtInput').attr('maxLength', 100);
Use HTML textarea with runat="server" to access it in server side.
This solution has less pain than using javascript or regex.
<textarea runat="server" id="txt1" maxlength="100" />
Note: To access Text Property in server side, you should use txt1.Value instead of txt1.Text
I tried different approaches but every one had some weak points (i.e. with cut and paste or browser compatibility). This is the solution I'm using right now:
function multilineTextBoxKeyUp(textBox, e, maxLength) {
if (!checkSpecialKeys(e)) {
var length = parseInt(maxLength);
if (textBox.value.length > length) {
textBox.value = textBox.value.substring(0, maxLength);
}
}
}
function multilineTextBoxKeyDown(textBox, e, maxLength) {
var selectedText = document.selection.createRange().text;
if (!checkSpecialKeys(e) && !e.ctrlKey && selectedText.length == 0) {
var length = parseInt(maxLength);
if (textBox.value.length > length - 1) {
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
}
}
}
function checkSpecialKeys(e) {
if (e.keyCode != 8 && e.keyCode != 9 && e.keyCode != 33 && e.keyCode != 34 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) {
return false;
} else {
return true;
}
}
In this case, I'm calling multilineTextBoxKeyUp on key up and multilineTextBoxKeyDown on key down:
myTextBox.Attributes.Add("onkeyDown", "multilineTextBoxKeyDown(this, event, '" + maxLength + "');");
myTextBox.Attributes.Add("onkeyUp", "multilineTextBoxKeyUp(this, event, '" + maxLength + "');");
Here's how we did it (keeps all code in one place):
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"/>
<% TextBox1.Attributes["maxlength"] = "1000"; %>
Just in case someone still using webforms in 2018..
Have a look at this. The only way to solve it is by javascript as you tried.
EDIT:
Try changing the event to keypressup.
The following example in JavaScript/Jquery will do that-
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function count(text, event) {
var keyCode = event.keyCode;
//THIS IS FOR CONTROL KEY
var ctrlDown = event.ctrlKey;
var maxlength = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val().length;
if (maxlength < 200) {
event.returnValue = true;
}
else {
if ((keyCode == 8) || (keyCode == 9) || (keyCode == 46) || (keyCode == 33) || (keyCode == 27) || (keyCode == 145) || (keyCode == 19) || (keyCode == 34) || (keyCode == 37) || (keyCode == 39) || (keyCode == 16) || (keyCode == 18) ||
(keyCode == 38) || (keyCode == 40) || (keyCode == 35) || (keyCode == 36) || (ctrlDown && keyCode == 88) || (ctrlDown && keyCode == 65) || (ctrlDown && keyCode == 67) || (ctrlDown && keyCode == 86))
{
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
}
function substr(text)
{
var txtWebAdd = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val();
var substrWebAdd;
if (txtWebAdd.length > 200)
{
substrWebAdd = txtWebAdd.substring(0, 200);
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val('');
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val(substrWebAdd);
}
}
This snippet worked in my case. I was searching for the solution and thought to write this so that it may help any future reader.
ASP
<asp:TextBox ID="tbName" runat="server" MaxLength="250" TextMode="MultiLine" onkeyUp="return CheckMaxCount(this,event,250);"></asp:TextBox>
Java Script
function CheckMaxCount(txtBox,e, maxLength)
{
if(txtBox)
{
if(txtBox.value.length > maxLength)
{
txtBox.value = txtBox.value.substring(0, maxLength);
}
if(!checkSpecialKeys(e))
{
return ( txtBox.value.length <= maxLength)
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
#Raúl Roa Answer did worked for me in case of copy/paste. while this does.
$("textarea[maxlength]").on("keydown paste", function (evt) {
if ($(this).val().length > $(this).prop("maxlength")) {
if (evt.type == "paste") {
$(this).val($(this).val().substr(0, $(this).prop("maxlength")));
} else {
if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
evt.returnValue = false;
evt.preventDefault();
}
}
}
});
you can specify the max length for the multiline textbox in pageLoad Javascript Event
function pageLoad(){
$("[id$='txtInput']").attr("maxlength","10");
}
I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function
This is the same as #KeithK's answer, but with a few more details. First, create a new control based on TextBox.
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyProject
{
public class LimitedMultiLineTextBox : System.Web.UI.WebControls.TextBox
{
protected override void Render(HtmlTextWriter writer)
{
this.TextMode = TextBoxMode.MultiLine;
if (this.MaxLength > 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
}
base.Render(writer);
}
}
}
Note that the code above always sets the textmode to multiline.
In order to use this, you need to register it on the aspx page. This is required because you'll need to reference it using the TagPrefix, otherwise compilation will complain about custom generic controls.
<%# Register Assembly="MyProject" Namespace="MyProject" TagPrefix="mp" %>
<mp:LimitedMultiLineTextBox runat="server" Rows="3" ...
Nearly all modern browsers now support the use of the maxlength attribute for textarea elements.(https://caniuse.com/#feat=maxlength)
To include the maxlength attribute on a multiline TextBox, you can simply modify the Attributes collection in the code behind like so:
txtTextBox.Attributes["maxlength"] = "100";
If you don't want to have to use the code behind to specify that, you can just create a custom control that derives from TextBox:
public class Textarea : TextBox
{
public override TextBoxMode TextMode
{
get { return TextBoxMode.MultiLine; }
set { }
}
protected override void OnPreRender(EventArgs e)
{
if (TextMode == TextBoxMode.MultiLine && MaxLength != 0)
{
Attributes["maxlength"] = MaxLength.ToString();
}
base.OnPreRender(e);
}
}
MaxLength is now supported as of .NET 4.7.2, so as long as you upgrade your project to .NET 4.7.2 or above, it will work automatically.
You can see this in the release notes here - specifically:
Enable ASP.NET developers to specify MaxLength attribute for Multiline asp:TextBox. [449020, System.Web.dll, Bug]
This is absolutely working:
use textarea and value
<div class="form-group row">
<label class="col-md-4 col-form-label">Description</label>
<textarea id="txtDescription" class="form-control" style="height: 40px ; width :250px; " runat="server" maxlength="500" tabindex="32" ></textarea>
</div>
</div>
In code:
While saving:-
BusinessLayer.Description = txtDescription.Value.ToString();
While taking back the value :-
txtDescription.Value = BusinessLayer.Description.ToString();
Important points:
Don't forget to use runat="server"
Don't forget to use value while converting
I know how to enable/disable individual validator controls on the client side using
ValidatorEnable(validator, false);
But how do you enable/disable all the validators within a ValidationGroup?
The validator properties aren't rendered as attributes unfortunately, so I don't know a good way to select them directly. You can try to iterate the Page_Validators array and filter out the ones you want to work with.
Try:
$.each(Page_Validators, function (index, validator){
if (validator.validationGroup == "your group here"){
ValidatorEnable(validator, false);
}
});
Check this blogpost explaining how with javascript. The main part of the code from the blog:
<script type="text/javascript">
function HasPageValidators()
{
var hasValidators = false;
try
{
if (Page_Validators.length > 0)
{
hasValidators = true;
}
}
catch (error)
{
}
return hasValidators;
}
function ValidationGroupEnable(validationGroupName, isEnable)
{
if (HasPageValidators())
{
for(i=0; i < Page_Validators.length; i++)
{
if (Page_Validators[i].validationGroup == validationGroupName)
{
ValidatorEnable(Page_Validators[i], isEnable);
}
}
}
}
</script>
Alternatively you can simply have ValidationGroup attribute with each validator defined .
Then you wont need any Jquery or javascript stuff to close them.
Here is the link that worked for me.
http://www.w3schools.com/aspnet/showasp.asp?filename=demo_prop_webcontrol_imagebutton_validationgroup
I have an ASP.NET code-behind page linking several checkboxes to JavaScript methods. I want to make only one JavaScript method to handle them all since they are the same logic, how would I do this?
Code behind page load:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX page JavaScript; obviously they all do the same thing for their assigned checkbox, but I'm thinking this can be reduced to one method:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
Add to the event the checkbox that is raising it:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
Afterwards in the function you declare it like this:
function checkBoxShowPrices_click(checkbox, e){ ...}
and you have in checkbox the instance you need
You can always write a function that returns a function:
function genF(x, y) {
return function(z) { return x+y*z; };
};
var f1 = genF(1,2);
var f2 = genF(2,3);
f1(5);
f2(5);
That might help in your case, I think. (Your code-paste is hard to read..)
Update:
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}
But I am wondering why it doesn't work when I add the else part.
Question:
I want to have a confirm dialog after user fills in all the data in the form.
I set onclientclick="return confirmSubmit()" in the submit button.
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
} else {
return false;
}
}
If Page_ClientValidate("Group1") returns false, the dropdownlist doesn't cause postback after I first select the item, and the postback only occurs when I select the dropdownlist second time.
What's the problem?
After Page_ClientValidate is called, the variable Page_BlockSubmit gets set to true, which blocks the autopost back. Page_BlockSubmit was getting reset to false on the second click, for what reasons I still don't fully understand. I'm looking more into this, but I have a solution and I'm under the gun so I'm rolling with it....
Just add below code in the code block which executes if Page is not valid.
Page_BlockSubmit = false;
e.g.
function ValidatePage()
{
flag = true;
if (typeof (Page_ClientValidate) == 'function')
{
Page_ClientValidate();
}
if (!Page_IsValid)
{
alert('All the * marked fields are mandatory.');
flag = false;
Page_BlockSubmit = false;
}
else
{
flag = confirm('Are you sure you have filled the form completely? Click OK to confirm or CANCEL to edit this form.');
}
return flag;
}
I have just found the solution. The following function works (remove the else part):
function confirmSubmit() {
if (Page_ClientValidate("Group1")) {
return window.confirm("Are you sure to submit the form?");
}
}