Refresh user control inside an update panel from javascript - javascript

I am working on a project where I want to refresh a part of the web page where i have a user control that contain dynamic data.user control will load data from a text file as this text file will update frequently. I need to refresh the user control alone not the whole page using javascript. I tried the following but it did not worked for me.
<%# Page Language="C#" %>
<%# Register src="ucTest.ascx" tagname="ucTest" tagprefix="uc1" %>
<script runat="server">
void button_Click(object sender, EventArgs e)
{
lbltest.Text = "Refreshed by server side event handler at " + DateTime.Now + ".<br>";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to update an UpdatePanel with JavaScript</title>
<script type="text/javascript">
function UpdPanelUpdate()
{
__doPostBack("<%= button.ClientID %>","");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Update the Panel
<asp:Button ID="button" runat="server" OnClick="button_Click" style="display:none;"/>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<ContentTemplate>
<uc1:ucTest ID="ucTest1" runat="server" />
<asp:Label ID="lbltest" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
my user control is.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ucTest.ascx.cs" Inherits="ucTest" %>
<table border="3">
<tr>
<td>
<% Response.WriteFile("TextFile.txt"); %>
</td>
</tr>
</table>
Here TextFile.txthas some information that will be changed frequently.
any help would be greatly appreciated.

To make things simpler, you can put the hidden button within the UpdatePanel so that you don't have to put async triggers. First keep the button visible and see if the update panel is refreshing or not. If yes then you can hide the button.
Next part is triggering the button by simulating click event. I will suggest you to use library such as jquery from cross-browser solution. For example,
function UpdPanelUpdate()
{
$("<%= button.ClientID %>").click();
}
For code __doPostBack("<%= button.ClientID %>",""); to work, you should try setting button's UseSubmitBehavior property as false.

Related

asp.net webform will not let me run javascript

I've just followed this very basic code on Youtube and it works perfectly. However, I go to try the same code on my asp.net webforms website, have tried it in both chrome and edge, and javascript doesn't seem to want to run. Can anyone please tell me where I am going wrong? I am using Visual Studio 2015. I must have a setting turned off somewhere or something as it does not make any sense to me why a basic alert is failing to run.
Here is the basic code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="webform.aspx.cs" Inherits="webform" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function pleaseWork(){
alert("this is running");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button"/>
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "pleaseWork();", true);
}
}
If you just need this to execute on the client, then you probably don't need any server side controls for it. So the head section doesn't need to run on the server.
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="pleaseWork();"/>
OR
<input type="button" value="Button2" onclick ="pleaseWork();" />
Your button is missing an onclick attribute, so Button1_Click is not being called.
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Dismissing a Bootstrap Dialog within an UpdatePanel

Clicking the "Show" button in the example below shows a simple bootstrap modal dialog with two buttons: Cancel (dismissed with data-dismiss), and "OK" which would presumably do some work on the server side, then call a bit of Javascript to hide the dialog.
The basic concept works fine--until I try to wrap the whole thing in an UpdatePanel as shown below. What the devil am I doing wrong? (And for bonus points, how would I attempt to set up a trace through Javascript which would have told me what I'm screwing up?)
Thanks!
Form Code:
<%# Page Language="VB" AutoEventWireup="false"
CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />
<script type="text/javascript" src="/includes/js/jquery-min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js">
</script>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1"
runat="server" ScriptMode="Debug">
</ajaxToolkit:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Panel ID="pnlTestPanel" runat="server" role="dialog"
CssClass="modal fade TestDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal"
aria-hidden="true">×
</button>
<h2 class="modal-title">Test Dialog</h2>
</div>
<asp:Panel runat="server" ID="pnlTestBody"
class="modal-body">
<label>This is a test dialog</label>
</asp:Panel>
<asp:Panel runat="server" ID="Panel3"
class="modal-footer">
<asp:Button ID="cmdOK" runat="server"
Text="OK"
CssClass="btn btn-warning">
</asp:Button>
<asp:Button ID="cmdCancel" runat="server"
CssClass="btn btn-default"
Text="Cancel"
data-dismiss="modal">
</asp:Button>
</asp:Panel>
</div>
</div>
</asp:Panel>
<asp:Button runat="server" Text="Show" ID="cmdShow" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Code-behind code
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub cmdShow_Click(sender As Object, e As EventArgs) Handles cmdShow.Click
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "pnlTestPanel", _
"$('#" & pnlTestPanel.ClientID & "').modal();", True)
End Sub
Protected Sub cmdOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOK.Click
' Do some server side work
' And now, close the dialog
ScriptManager.RegisterStartupScript(Me.UpdatePanel1, UpdatePanel1.GetType(), _
"Hide Test Dialog", "$('.TestDialog').modal('hide');", True)
End Sub
End Class
The ScriptManager.RegisterStartupScript will only work when you there is a full PostBack. In your case the PostBack occurs inside an UpdatePanel.
You will need to use the JavaScript events that ASP.NET has when an UpdatePanel is updated.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
console.log('UpdatePanel start');
}
function EndRequestHandler(sender, args) {
console.log('UpdatePanel end');
}
You need to put your code in the EndRequestHandler event to close the modal.
For more info you can read here and here.
Even if button is inside an update panel, the script manager will still work as you are passing updatepanel & not the page as its parameter..
There is only one thing missing.
Write this statement inside your Register startup script.
$(document).ready(function () {
$('.TestDialog').modal('hide');
});
The best approach I found was to create a simple javascript function.
function closeModal(modalid) {
$('#' + modalid).modal('hide');
}
Then, in your various Modals on the page, you can set a OnClientClick value of the Submit/Create button to "closeModal('id_of_your_modal_container');"
I can then use UpdatePanels with Triggers, as well as all the normal trimmings I want on the page (Toastr notifications etc), and it works very seamlessly. If it's just a standard button or anchor tag then setting a data attribute is all you need 'data-dismiss="modal"'

CustomValidator client function not firing for empty textbox

I have mocked up a very simple page and I am absolutely stumped as to why the javascript wont fire when I tab between the 2 textboxes:-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" inherits="Checkout_test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>c</title>
<script type="text/javascript">
function checkthisvalue(source, args) {
alert('hello');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lbl1" AssociatedControlID="txtUsername" Text="1:" runat="server" />
<asp:TextBox runat="server" CssClass="username" ID="txtUsername" ValidationGroup="vg"></asp:TextBox>
<asp:CustomValidator Enabled="true" ID="cvUsername" Display="Dynamic" ValidationGroup="vg" ControlToValidate="txtUsername" EnableClientScript="true" ClientValidationFunction="checkthisvalue" ValidateEmptyText="true" runat="server">*</asp:CustomValidator>
<asp:Label ID="lbl2" AssociatedControlID="txtPassword" Text="2:" runat="server" />
<asp:TextBox runat="server" CssClass="username" ID="txtPassword"></asp:TextBox>
<asp:CustomValidator Enabled="true" ID="cvPassword" Display="Dynamic" ControlToValidate="txtPassword" EnableClientScript="true" ClientValidationFunction="checkthisvalue" ValidateEmptyText="true" runat="server"></asp:CustomValidator>
</div>
</form>
</body>
</html>
Note that both CustomValidators have ValidateEmptyText=true
I've tried this in IE and Chrome with no luck.
I guess it is not a problem of empty text. The CustomValidator won't fire upon tab navigation only if you don't change the control value. (try to put a value in your TextBox, navigate with tab, come back to empty the TextBox, and navigate again with Tab. The CustomValidator will fire)
When thinking about it, having the validators firing upon a simple tab navigation would be somewhat disturbing for the user.
Anyway, the validators will fire upon form submission (provided you remove the ValidationGroup attributes on first TextBox and Validator), and value changes, which is what they are supposed to do.
Hope this will help,

How to disable asp.net validator on client side?

I have very simple aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:textbox runat="server" ID="tbText" ValidationGroup="Address"></asp:textbox>
<br />
<asp:RequiredFieldValidator ID="rfvText" runat="server" ControlToValidate="tbText"
ValidationGroup="Address" ErrorMessage="RequiredFieldValidator">Enter text</asp:RequiredFieldValidator>
<br />
<asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="Submit_Click"
ValidationGroup="Address" OnClientClick="DisableValidator();" />
<script type="text/javascript">
function DisableValidator() {
alert('Called and disable validators before submit');
var validator = document.getElementById("<%=rfvText.ClientID%>");
validator.validationGroup = "someGroup";
ValidatorEnable(validator, false);
}
</script>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
Validate("Address");
if (!IsValid)
{
throw new Exception("Page is no valid");
}
}
}
All elements on the page have ValidationGroup="Address", but I need disable my validator just before I click on the button. So, on client site it disables, but when I try to validate it on the server, my page isn't valid on the server but valid on client.
How can I disable validator on client to became disable on the server also?
Thanks!
You should use EnableClientScript="False" on the validation control, that is:
<asp:RequiredFieldValidator ID="rfvText"
runat="server" ControlToValidate="tbText"
ValidationGroup="Address"
EnableClientScript="False"
ErrorMessage="RequiredFieldValidator">Enter Text
</asp:RequiredFieldValidator>
You would have to programmably disable it when the page posts back, however you interpret that validator should be disabled on the client then would need to be replicated on the server, and set Enabled="false".
If you are using .NET 4, try using the EnableClientScript property. I've never used it myself but according to the docs, it should meet your needs.
Gets or sets a value indicating whether client-side validation is enabled.
<asp:Button runat="server" Text="Click Me" EnableClientScript="False" />

jQuery function before the Postback for FileUpload in ASP.NET

So, I have an .aspx webpage as follows:
..
<form id="frm" runat="server">
<asp:FileUpload runat="server" id="fileupload" onchange="browsed()" />
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton" class="uploadbutton" Text="start upload" Enabled="false" />
<div id="nfo" style="display: none">
blabla
</div>
</form>
..
Now, as you can guess correctly, user chooses file to upload, clicks #uploadbutton and, voila, Upload_Click is called after the postback.
Then, I want to show div #nfo with some jQuery effects during the upload. To do this, I write:
$(function() {
$('.uploadbutton').click(function() {
$('#nfo').slideDown().show("fast");
})
})
and everything works just fine, until the user starts browsing in IE...
First of all, in IE, user has to click #uploadbutton twice - first time to display #nfo, second time, for some reason, to initiate postback.
Secondly, after the postback, Upload_Click's this.fileupload.HasFile shows false.
FF and Chrome works quite well though.
As far, as I can understand this - in IE jQuery's function prevents something important for asp:FileUpload from happening and stops the postback. Though, on the second click it does initiate the postback, but still with no info for asp:FileUpload's Upload_Click.
Any help?
Update:
followed #joelt'd advice. turned out, there was some different problem, never thought it could be of importance, so I didn't provide source code for that part =(
see localizing <asp:FileUpload>. IE problem
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
$("#progress").show();
});
});
</script>
</head>
<body>
<form runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<div id="progress" style="display:none; background-color:Red;">test</div>
</form>
</body>
</html>
This works fine for me in FF and IE7, except in IE, the progress indicator doesn't really give you anything because of how it's rendering, I suppose. I would say the biggest difference between our code is the "onchange=browsed()" function. It's possible that's not getting called until you click the button? In any case, I would start with a stripped down page like this, and start adding in other elements you have until it breaks.
try this:
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton"
class="uploadbutton" Text="start upload" Enabled="false"
OnClientClick="return myFunction();"/>
<script type="text/javascript">
function myFunction(){
$('#nfo').slideDown().show("fast");
return true;//THIS WILL FIRE POSTBACK EVENT
//return false;//THIS WILL STOP POSTBACK EVENT, WHICH YOU MAY WANT IF THERE
//IS NO FILE SELECTED
}
</script>

Categories

Resources