Asp.net auto response to client - asp.net

I have this table on my sql server database:
name
family
address
and i have a 2 user's:
User A
User B
i want to when User B insert new record into the table,show in User A gridView.
i use this solution:
User A web browser has a this code:
<script type="text/javascript">
$(document).ready(function () {
setTimeout("RefreshPage()", 5000);
});
function RefreshPage() {
/* var url = "GetOrder.aspx";
$(location).attr("href", url);
*/
location.reload();
};
</script><br/>
that code refresh User A webpage every 5 second and in page load event i write a simple code to run select query and show in gridview.
this method very crazy solution to do this.
can i use other solution and how?

Your code Refresh whole page. Use below code, it will refresh only contain. :)
<asp:ScriptManager ID="scp1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:GridView ID="yourGrid" runat="server"></asp:GridView>
<asp:Button id="btnAutoRefresh" runat="server" style="display:none"
onclick="btnAutoRefresh_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
$(document).ready(function () {
setInterval("RefreshPage()", 5000);
});
function RefreshPage() {
$("#<%=btnAutoRefresh.ClientID %>").trigger("click");
};
</script>
// code behind
protected void btnAutoRefresh_Click(object sender, EventArgs e)
{
// code for Bind Grid
}

You need to use client notification technique, for example SignalR. You can read more about it here

Related

How to display value in the SimpleModal's dialog?

my question is really simple. I have a asp.net button. I can use it to call the simpleModal and have a dialog displayed. Now, I added a label control in the dialog, and would like this label to display some value. What should I do?
Here is my codes
$('#<%= btnOpen.ClientID %>').click(function(e) {
e.preventDefault();
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close(); // must call this!
});
});
});
}
});
e.preventDefault();
// return false;
});
<asp:Button ID="btnOpen" runat="server" Text="ASP.NET Open"/>
<div id="content" style="display: none;">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
I assume since you said that your question is simple that you just have an unfamiliarity with jQuery. You can put this in your click function, or in the $(document).ready function, depending on your full requirements:
var yourValue = ; // put your function or value here
$('#Label1').text(yourValue);
Note: You'll need to use .html instead of .text if you have a string with tags, but .text is faster.
Lol, I am answering my own question again, but I will give credit to mNVhr tho.
I finally get the whole thing work. The trick for asp.net button to fire a postback, along with javascript's postback, is to put the asp.net button into an update panel. Here is the code I have
For the javascript part:
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.simplemodal-1.3.5.js" type="text/javascript"></script>
<script type="text/javascript">
function myOpen() {
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close();
});
});
});
}
});
}
function myClose() {
$.modal.close();
}
</script>
For the HTML markup
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnOpen" runat="server" Text="Open" OnClick="btnOpen_Click" OnClientClick="myOpen();" />
</ContentTemplate>
</asp:UpdatePanel>
<div id='content' style="display: none">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<input id="Button2" type="button" value="Close" onclick="myClose();" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
For the code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
private void CloseDialog()
{
string script = string.Format(#"myClose()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "1")
CloseDialog();
else
Label2.Text = TextBox1.Text;
}
protected void btnOpen_Click(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Now.ToString();
UpdatePanel1.Update();
}
I hope this tiny code can help those asp.net developer who want to use the nice jQuery in their projects.
As you can see, from the above codes.
When I click on the btnOpen button, two postbacks fired. One is from the asp.net code behind, which assign current datetime to the textbox control inside the modal dialog. The second postback is from the javascript, which open the modal dialog. The asp.net button has to be inside the update panel. Otherwise, the modal dialog will only stay for about 0.5 second.
When I click on the btnSave inside the modal dialog. Postback also occurred. I have a little logic here. When the textbox's value is 1, I call the closeDialog() function. When the value is other numbers, the modal dialog stay opening, and the label control inside the dialog will display the number from the text box.
jQuery is nice, but as a .Net developer, it is just new, and sometimes difficult for me to understand it, especially for the conflict of postbacks between javascript and .net.
I hope this answer is helpful.

jquery ui datepicker inside asp.net UpdatePanel

I have a web page, where I'm using a jQuery UI datepicker on an asp.net textbox, which is located inside an UpdatePanel. Here is a description of what I do roughly
<script type="text/javascript">
$(document).ready( function() { $(".datepicker").datepicker(); } );
</script>
<asp:UpdatePanel ... >
...
<asp:TextBox runat="server" CssClass="datepicker" />
<asp:Button runat="server" />
...
</asp:UpdatePanel>
When I first load the page, everything works fine. When clicking inside the textbox, the datepicker pops up. But when I click the button, and an async postback is executed, the datepicker no longer pops up, when I click the field again.
I know that the problem is because the UpdatePanel completely replaces all the contained HTML when it is updated, so in effect, it is a new text field, which has not been initialized with the datepicker functionality.
I guess that I should not use $(document).ready() here to initialize my datepickers, but where is a good place to place the initialization code? Or is there a way that I can retrigger the initialization code after an AJAX update?
add the script behind , that's what I do.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(evt, args) {
$(".datepicker").datepicker();
});
</script>
Add this script at the end of your page.
Replace the initialize() function with whatever code you want to run every time there is a partial postback from an updatepanel.
<script type="text/javascript">
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
initialize();
}
}
</script>
Replaces the class name '.datepicker' by the name of the object within the page.
Example:
<script type="text/javascript">
$(document).ready( function() { $("#<%=DateTextBox.ClientID %>").datepicker(); } );
</script>
<asp:UpdatePanel ... >
...
<asp:TextBox runat="server" ID="DateTextBox"/>
<asp:Button runat="server" />
...
</asp:UpdatePanel>}
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler() { $(".datepicker").unbind().mask("99/99/9999").datepicker() };
$.getScript("../Scripts/jquery.maskedinput.min.js", function () {
$(".datepicker").mask("99/99/9999");
});
$.getScript("../Scripts/jquery-ui-1.11.3.min.js", function () {
$(".datepicker").datepicker()
});
});

JQuery DIalog and ASP.NET Repeater

I have an ASP.NET repeater that shows a list of items with a delete LinkButton.
I want to setup the Delete LinkButtons to show a JQuery Dialog for a confirmation. If the "OK" button is clicked, I want to do the postback.
The obvious problem is that each LinkButton in the repeater will have it's own ID and I don't want to have to duplicate all the javascript for the dialog.
Suggestions ?
The solution is not so simple. You must have the ability to call the original callback function after pressing the Ok button of jQuery UI Dialog.
First you need a generalized js function for showing the dialog:
function showConfirmRequest(callBackFunction, title, content)
{
$("#divConfirm").html(content).dialog({
autoOpen: true,
modal: true,
title: title,
draggable: true,
resizable: false,
close: function(event, ui) { $(this).dialog("destroy"); },
buttons: {
'Ok': function() { callBackFunction(); },
'Cancel': function() {
$(this).dialog("destroy");
}
},
overlay: {
opacity: 0.45,
background: "black"
}
});
}
I supposed the presence of a div like
<div id="divConfirm"></div>
On c# code-behind you have to register the previous client function, passing the original asp.net callbackFunction of your control as parameter (I generalized):
protected void AddConfirmRequest(WebControl control, string title, string message)
{
string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
string function = String.Format("javascript:showConfirmRequest(function() {{ {0} }}, '{1}', '{2}'); return false;",
postBackReference,
title,
message);
control.Attributes.Add("onclick", function);
}
Through the method GetPostBackEventReference you have the ability to retrieve the postback function that asp.net assign to the control.
Now, on Repeater ItemDataBound, retrieve the control that execute the delete and pass it to this function:
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_OnItemDataBound">
...
<ItemTemplate>
...
<asp:Button ID="btnDelete" runat="server" Text="Delete" />
...
</ItemTemplate>
</asp:Repeater>
and the code:
protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
WebControl btnDelete = ((WebControl)e.Item.FindControl("btnDelete"));
AddConfirmRequest(btnDelete, "Confirm delete", "Are you sure? Really???");
}
}
I hope this helps.
<asp:GridView ... CssClass="mygridview"></asp:GridView>
and
$('table.mygridview td a').whatever()
That will allow you to work with all the link buttons simultaneously.
You can make it like this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>
or i think you could also make it like this:
<script>
$(function() {
$(".button").click(function() {
return confirm("Delete this record?");
});
});
</script>
in the ConfirmDelete Method, you can define your jQuery Confirm dialog
The question is definitely answered by tanathos, but I have another option working that avoids scripting in the code-behind if you are so inclined. I just hid the asp delete button using display:none and added a delete button that invokes the confirmation dialog and clicks the hidden asp delete button if the delete is confirmed.
The HTML in the repeater:
<ItemTemplate>
...
<td>
Delete
<asp:Button ID="DeletePolicyButton" runat="server" OnCommand="OnDeleteCommand" CommandArgument="Argument" Text="Delete" CssClass="delete-button" />
</td>
...
</ItemTemplate>
The CSS:
.delete-button
{
display: none;
}
The javascript:
// make the dummy button look like a button
$("a.dummy-delete-button").button({
icons: {
primary: "ui-icon-trash"
}
});
// create the dialog
var deleteDialog = $('<div>Are you sure you want to remove this policy?</div>')
.dialog({
autoOpen: false,
modal: true,
title: 'Delete Policy'
});
// handle click event to dummy button
$("a.dummy-delete-button").click(function (e) {
// don't follow the href of the dummy button
e.preventDefault();
// get a reference to the real ASP delete button
var button = $(this).closest('td').find('.dummy-delete-button');
deleteDialog.dialog({
buttons: {
// handle delete. Note: have to defer actual button click until after close
// because we can't click the button while the modal dialog is open.
"Delete": function () { deleteDialog.bind("dialogclose", function () { button.click() }); $(this).dialog("close"); },
// handle close
"Cancel": function () { $(this).dialog("close"); }
}
});
deleteDialog.dialog("open");
});
Hy,
First you should use Jquery Dialog or other clienside dialogs, it's more cooler.
You should have an html element on the page to invoke the Jquery dialog popup.
<div class="Popup"></div>
<script>
var confirm = false;
function ConfirmDelete(doPostback) {
$(".Popup").dialog(){ /* threat the dialog result , set confirm variable */ };
if(confirm) {
__doPostback(); }
else return false;
}
</script>
On the part where i put the comented sentence you can put code to handle the dialog result.
You could find info from the link above.
The function is returning false and because of that it blocks the execution of the server side code (the async postback).
The Button should look like:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton OnClientClick="ConirmDelete(<#%GetPostbackReference()%>)" CommandArgument = "<%# DataBinder.Eval(Container.DataItem, "Id") %>" OnClick="btnConfirm_Click" ID="btnConfirm" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
On the CommandArgument property i set the id of the item wich are binded to the repeater.
In this way on the btnConfirm_Click event you have acces to this paramater
void btnConfirm_Click(object sender, CommandEventArgs e)
{
e.CommandArgument -> you will find the id an you can execute the delete
}
You should have on the code behind:
protected string GetPostbackReference()
{
return Page.ClientScript.GetPostBackEventReference(btnConfirm, null);
}
This function is invoked on the binding of the element and returning the current controls postback method wich will look like __doPostback(source, param)
This is a javascript method wich you could excute easilly,and you have full control of the postbacks.
On clientside you can decide whether or not to call this postback event.
PS: If something is unclear post here a question and i will update the answer.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>

Firing the JQuery Dialog using an ASP.NET Button?

I have a Page which has a Control on it with 2 textboxes (username and password) and an asp:Button. If the user's membership is going to expire within 30 days and the button is clicked, I want the JQuery dialog to popup. Inside the JQuery dialog, I have some text and an asp:LinkButton. The link button has an event attached to it, but it is not being fired when I click it in the dialog box. Here is the script tags for the JQuery:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="ui.core.js"></script>
<script type="text/javascript" src="ui.draggable.js"></script>
<script type="text/javascript" src="ui.resizable.js"></script>
<script type="text/javascript" src="ui.dialog.js"></script>
Here is the script the dialog: For testing, I am closing the dialog on Renew Membership click, but I actually want it to fire a method I create in asp.net to direct the user to a another page and pass a session variable.
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog({
// autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() { $(this).dialog("close"); } }
});
});
</script>
<asp:Content ID="mainContent" runat="server" ContentPlaceHolderID="Content">
<div id="dialog" title="Membership Renewal">
<p>Uh Oh! Your membership is going to expire.</p><br />
<p>Hurry up and renew today!</p><br />
<asp:LinkButton runat="server" Text="Click Here to Renew"
onclick="Unnamed2_Click"></asp:LinkButton>
</div>
Here is the click event for the LinkButton:
protected void Unnamed2_Click(object sender, EventArgs e)
{
UserProfiles userProfile = (UserProfiles)Session["userProfile"];
Response.Redirect("~/Renew.aspx");
}
What should happen is that when the user clicks the sign-in button, it should popup up the dialog only if the days they have left to expire is <= 30 and if they do, they have the option of clicking the link in the dialog and going to a renew page where I want to pass it a Session variable with a Profile, but that is not being called, so I guess, I would like to know is how can I add the event handler of the button to the dialog and is there a way to set it so that it only comes up once, for example adding a cookie to the users browser and only showing it if they don't have a cookie set.
I believe this is more of an ASP.NET issue and not a jQuery dialog issue.
I wouldn't use the onClick and PostBackUrl within the same LinkButton. So, take off the PostBackUrl attribute and instead use
protected void Unnamed2_Click(object sender, EventArgs e){
UserProfiles userProfile = (UserProfiles)Session["userProfile"];
Response.Redirect("~/Renew.aspx");
}
If you only need to show the control when the user is > 30 days. I would create a user control.
jquery.renewDialog.js
$(document).ready(function() {
$("#dialog").dialog({
modal: true
});
});
RenewalUserControl.ascx
<asp:ScriptManager runat="server" id="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="jquery.renewDialog.js" />
</Scripts>
</asp:ScriptManager>
<div id="dialog" title="Membership Renewal">
<p>Uh Oh! Your membership is going to expire.</p><br />
<p>Hurry up and renew today!</p><br />
<asp:LinkButton runat="server" Text="Click Here to Renew"
onclick="Unnamed2_Click" />
</div>
Login.aspx
<uc1:RenewalUserControl runat="server" ID="RenewalUserControl1" Visible="false" />
Login.aspx.cs
if (user.IsExpired)
{
RenewalUserControl1.Visible = true;
}

Working with Gridviews and File Transfers

I need to generate a Excel sheet during RunTime on a ItemCommand_click event in a GridView and transfer the file and then re-bind the GridView with the status change.
As we redirect the response with File transfer , How could I update the GridView?
I was looking to do something very similar on selected index change on the rows to output a reporting services report as a PDF. I was only able to get this to work with a response.redirect to another page that handled the output of the file. It looks like your issue really becomes the rebinding the grid after the status change, if you do a response.redirect, you can't touch your grid...
Take a look at this code. I found it on encosia.com. It looks like you might be able to use the iFrame for your output, and then you can use a JavaScript call to postback the page to rebind the grid maybe.
<html>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<script language="javascript">
// Get a PageRequestManager reference.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Hook the _initializeRequest event and add our own handler.
prm.add_initializeRequest(InitializeRequest);
function InitializeRequest(sender, args)
{
// Check to be sure this async postback is actually
// requesting the file download.
if (sender._postBackSettings.sourceElement.id == "DownloadFile")
{
// Create an IFRAME.
var iframe = document.createElement("iframe");
// Get the desired region from the dropdown.
var region = $get("Region").value;
// Point the IFRAME to GenerateFile, with the
// desired region as a querystring argument.
iframe.src = "GenerateFile.aspx?region=" + region;
// This makes the IFRAME invisible to the user.
iframe.style.display = "none";
// Add the IFRAME to the page. This will trigger
// a request to GenerateFile now.
document.body.appendChild(iframe);
}
}
</script>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="Region">
<asp:ListItem Value="N">North Region</asp:ListItem>
<asp:ListItem Value="W">West Region</asp:ListItem>
<asp:ListItem Value="SE">Southeast Region</asp:ListItem>
</asp:DropDownList>
<asp:Button runat="server" ID="DownloadFile" Text="Generate Report" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
The page that handles the download...
protected void Page_Load(object sender, EventArgs e)
{
string FileResponse;
string Region = Request.QueryString["Region"];
// Code here to fill FileResponse with the
// appropriate data based on the selected Region.
Response.AddHeader("Content-disposition", "attachment; filename=report.csv");
Response.ContentType = "application/octet-stream";
Response.Write(FileResponse);
Response.End();
}

Resources