bootstrap alert from server side - c#

I'm a newbie. I need to be shown a notification using bootstrap when executing server code. only the written code works for me. I do not know how to call a notification when executing code.
static MessageBox()
{
// Create the store
pageTable = new Dictionary<Page, Queue>();
}
public static void Show(string str)
{
// Lets find out what page is sending the request
Page page = HttpContext.Current.Handler as Page;
// If a valid page is found
if (page != null)
{
// Check if this page is requesting message show for the first time
if (pageTable.ContainsKey(page) == false)
{
// Lets create a message queue dedicated for this page.
pageTable.Add(page, new Queue());
}
// Let us add messages of this to the queue now
pageTable[page].Enqueue(str);
// Now let put a hook on the page unload where we will show our message
page.Unload += new EventHandler(page_Unload);
}
}
static void page_Unload(object sender, EventArgs e)
{
// Lets find out which page is getting unloaded
Page page = sender as Page;
// If a valid page is found
if (page != null)
{
// Extract the messages for this page and push them to client side
HttpContext.Current.Response.Write
("<script>alert('" + pageTable[page].Dequeue() + "');</script>");
}
}
but this is a standard page notification.
the call occurs as follows
<asp:LinkButton runat="server" id="LinkButton1" cssclass="badge badge-pill badge-info" commandargument='<%#Eval("tabel")%>' commandname="tabel">tur</asp:LinkButton>
MessageBox.Show("test message");

Well, it really depends on the bootstrap dialog or say "toast" message you looking to display.
For a pop dialog (say confirm to delete), I find jQuery.UI gives you MUCH more control. (and you can control the location of the pop dialog).
For a "message" notificaiton, then I suggest say jQuery toast.
So, in this form for example, I have a delete button. And in fact the WHOLE form was popped as a dialog from the grid view behind:
Then when I clicked on the delete button, I poped another dialog to confirm the delete.
The code to pop that delete dialog was a js routine. And if it returns true, then the server side button runs, and if false, then the server side button code does NOT run.
The button code looked like this:
<button id="cmdDelete" runat="server" class="btn myshadow" style="margin-left:15px"
type="button"
onserverclick="cmdDelete_ServerClick"
onclick="if (!MyConfirmDel(this)) {return false};" >
<span aria-hidden="true" class="glyphicon glyphicon-trash"> Delete</span>
</button>
So, I have both a server side event (plane jane .net code).
And I have a client side event - JavaScript.
So, the js routine MyConfirmDel(this) runs the client side js code, and that was this:
var MyConfirmDelOK = false
function MyConfirmDel(Btn) {
if (MyConfirmDelOK) {
MyConfirmDelOK = false
return true
}
var myDialog = $("#mydelpop");
myDialog.dialog({
title: "Delete Hotel",
width: "26em",
modal: true,
dialogClass: 'ui-widget-shadow',
position: { my: "left top", at: "right bottom", of: Btn },
buttons: {
Delete: function () {
myDialog.dialog('close')
MyConfirmDelOK= true
$(Btn).click()
},
cancel: function () {
myDialog.dialog('close')
}
}
});
}
But, maybe by notification you mean a toast message:
So, when I for example hit this button, I get a pop dialog to confirm (works like above), and then I trigger a toast message.
I have BOTH routine setup to pop dialogs from the server side code, and also a toast message routine that shows a notification as jquery toast.
This example:
the server side code to pop the notification is this:
Protected Sub cmdReSet_ServerClick(sender As Object, e As EventArgs)
MySqlExecute("exec MyRestore")
GridView1.DataBind()
MyToast(Me.Page, cmdReSet.ClientID, "Data Restored", "Data re-set back to original", "6000")
End Sub
And MyToast routine is this that injects the js routine to run.
Sub MyToast(my As Page, ctrlBeside As String, Heading As String,
strText As String,
Optional strDelay As String = "3000")
' same as Mytoast, but a js function called toastcall()
' MUST be placed on the page
' any master page will have this function
' ctrlBesite - do NOT pass # - so Button1 you pass "Button1"
Dim strScipt As String =
"toastcall('#ctrlBeside','#Heading','#Text','#strDelay');"
strScipt = strScipt.Replace("#ctrlBeside", ctrlBeside)
strScipt = strScipt.Replace("#Heading", Heading)
strScipt = strScipt.Replace("#Text", strText)
strScipt = strScipt.Replace("#strDelay", strDelay)
ScriptManager.RegisterStartupScript(my, my.GetType(), "mytoast", strScipt, True)
End Sub
So, it not clear if you looking for a pop dialog or confirm dialog to be triggered from server side code, or a toast like notification that you want to display, and use server side code to do this as per above.
If you want say a "working - please wait" notification, then I suggest the above toast message. (set the toast message to much longer then the processing routine). when your code behind is done, then the page life cycle is completed, and the toast message will go away without any additonal code.
So, attach a client side and server side event to the one button. You click, and the client side toast message will appear, and THEN your server side code runs. When done, with a post-back cycle complete, then as noted, the toast message, or even dialog message will go away on its own.
I love the look and feel of the bootstrap dialogs, but they are a royal pain to position on the form, and even more of a pain to easy pop with js code, so I used jquery.UI dialogs as a result. You get MUCH better control in code, but as noted, I don't particular like the look and feel of the jQuery.UI dialogs - they look somewhat dated.
so you can as the above toast message routine shows, EASY trigger a message from the server side, but it going to occur AFTER the button code (server side) processing is done. If you need the toast message to appear at button click time, then you HAVE to trigger that with client side code.
I suppose you could use server side code, but you would have to:
load up - set the js routine to run + display - allow page code to complete
then in js code, display message, and then trigger another post back
In this case, as noted, better would be to have a client side message event appear, and then have the client side js code THEN call a web method. When the web method is done, then upon return from the web method call, you can close your dialog. This approach is probably the best, but you you wanting to trigger this from code behind, the you have to split this out into two routines:
First routine - trigger js code (like I did for toast)
That first routine ALSO THEN can call a web method while the message is display, and when done, hide message.
So, you can't for example place both the "please wait" and have a long running process occur in the SAME routine (code behind). (the exception I suppose would be adopting SignalR -- which is quite a big system and adopting for what amounts to the goal of a simple message is over kill).

Related

ASP.NET WebForms Confirm

I'm new to web programming with .NET.
I am developing a web page with webforms, and I want at a certain moment to programmatically show a modal window, for the user to accept or cancel, according to a question. Exactly what does the "confirm" function of JavaScript.
I tried to get it calling a JavaScript function:
Page.ClientScript.RegisterStartupScript (this.GetType (), "CallMyFunction", "MyFunction()", true);
But I need to do it without reloading the page, and I also need to control if the user has accepted or canceled and I do not know how to do it.
I've also tried getting it using the ModExPopupExtender control from DevExpress.
Can someone tell me a simple way to get what I want?
I can not understand how something so usual in web programming, and that PHP + javascript would not pose any problem can be so complicated.
All start in a one-button event on the code behind:
protected void btn1_Click(object sender, EventArgs e)
{
//I make a series of checks
//If certain conditions I want to show the confirm
//According to the user has chosen ok or cancel will perform a certain action
}
Onclientclick does not help me because before launching the "confirm" I have to do some checks on the server side.
Thank you very much.
You can use OnClientClick which is a property on most web controls.
I like to just bring up a simple confirm() dialog which executes the server code if the user clicks OK and does nothing if the user cancels the action:
<asp:Button runat="server" ID="btnSave" Click="btnSave_Click" Text="Save"
OnClientClick="return confirm('Are you sure you want to do this thing?');" />
You can do other things with it as well, but the key thing to remember is that anything you do in OnClientClick will happen before the page gets posted back to the server.
This is also perfectly valid:
<asp:Button runat="server" ID="btnSave"
OnClientClick="showModalConfirm('some message goes here');" ... />
<script>
function showModalConfirm(msg)
{
$(".modal .message").innerHtml(msg);
$(".modal").Show();
}
</script>
You can set the action that OnClientClick should perform in your codebehind in exactly the same way:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you want to do this thing?');";
}
You can use below code in c# to call javascript function. Below code will execute afterpostback() javascript function:
ClientScript.RegisterStartupScript(GetType(), Javascript, "javascript:afterpostback();", true);
And you can write code in javascript function to display any div or popup:
<script language="javascript" type="text/javascript">
function afterpostback() {
//Here you can write javascript to display div/modal
}
</script>
One way I've handled this previously was to have 2 buttons on the page. The first would be initially visible and labeled "Submit". The second would be initially hidden and labeled "Confirm". The "Submit" button would postback upon click and perform your server side checks/validation. If those checks failed, an appropriate error message would be displayed. If those checks passed, an appropriate "Please confirm your submission"-type message would be displayed, the "Submit" button would become hidden, and the second "Confirm" button would become visible. When that Confirm button was clicked, it would postback again and fully submit.
EDIT: I forgot to mention, there's a bit more to this that occurred to me after I initially posted. You'll have to protect the fields from being edited in the event the server-side verification is successful as you obviously don't want the user changing values and then clicking the Confirm button. That means disabling all the input controls - which could be a pain if you have a lot. You also have to give them a way to (intentionally) Edit in case the server side verification passes, you display the Confirmation, and they change their minds - so basically you'd need a third "Cancel/Edit"-type button that would put the form back in edit mode and show your initial Submit button.

Run Javascript when Asp.net page is loading

I wonder if there is way to run JS code whenever a asp.net page is contacting the server.
I.e. I'm looking for a general event handler that is triggered whenever a call to the server is made for runat="server" components.
I know there's a way to get jQuery.ajax() to run JS code before and after a call to the server is made, but I'm not sure how to do it in asp.net. Especially, since this projects uses a lot of custom components.
The goal here is to show some kind of loading image when a button is clicked, to prevent the user to click a button twice and also to show the user that the system is working.
If the click causes the page or an updatepanel to refresh, I'd only like to display the loading image before the refresh, eg. User clicks, "loading" is shown, page/update panel is refreshed (causing the "loading" to disappear), the new page/content is displayed as normal.
Update 1:
I can't use UpdateProgress because some of the buttons aren't inside UpdatePanels. What I really want to do is to fire a JS as soon as any button/control that will contact the server is clicked. I.e. if the user clicks a dropdown which doesn't contact the server, nothing should happend. But if that dropdown has any connection to the server, a JS should be run.
I understand that this is ASP.NET Ajax and not jQuery Ajax, I only used jQuery as an example. Because I've used a jQuery method before (with jQuery Ajax) to trigger JS before the server call was made. Eg. to lock the element that was clicked or to display a "Loading..." screen.
I could of course add a bit of a JS hack to every page which adds a "onclick" event to every button manually, but I thought it would be better if there was a general solution for this (since I've got lots of pages, each with a few buttons that contact the server on them).
Update 2:
When I think about it, it doesn't necessarily need to be a JS that is triggered. It would be good enough if the page somehow only made sure that the same button wasn't clicked twice. Either by disabeling the button or by adding something in front of it (like a "Loading..." screen).
You can use an UpdateProgress for this to use with update panels, but if you are doing a full page postback (i.e. not ajax) the only loading animation you can have is the browsers own.
UpdateProgress:
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
Shiny loading aninmation
</ProgressTemplate>
</asp:UpdateProgress?
Here is how you can do it using jquery:
$(function() {
$('a[href]').on('click', function(e) {
var self = this;
e.preventDefault();
loadAsync($(self).attr('href'));
});
});
function loadAsync(url) {
$('div#result').fadeOut(200, function() {
$('div#loader').fadeIn(200, function() {
$.get(url, function(data) {
$('div#result').html($(data));
}).done(function() {
console.log('done');
}).fail(function() {
$('div#result').html('Error');
}).always(function() {
$('div#loader').fadeOut(200, function() {
$('div#result').fadeIn(200);
});
});
});
});
}

Javascript confirm box in C# code behind

I am trying to show a javascript confirm box in the middle of some server side code and after getting user confirmation continue processing but confirm box does not show up. I even wrote some sample code but no success.
after some server processing I need to ask user a question and after user confirmation continue some other server code. it seems to be very simple. even alert box work. How can I solve it?
please note that I can not call javascript confirmbox straight from buttonclick I need to do some serverside code and if that was ok then I want to show a confirmbox for continuation.
here is the code
<asp:Button ID="btn_deletefromDB" runat="server" OnClick="btn_deletefromDB_Click" Text="Delete from Datatbase);" />
protected void btn_deletefromDB_Click(object sender, EventArgs e)
{
//Delete service from Database
// some server side processing code
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Do you want to delete it from runtime too? Click OK to proceed.');", true);
Label1.Text = "delete from runtime confirmed";
// continue and delete from runtime
//bla bla bla
}
Instead of triggering this in the code-behind, you should add it to the Button1 OnClientClick event like so:
<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Do you want to delete it? Click OK to proceed.');" OnClick="Button1_Click" />
Web applications do not work like this. You cannot ask for user input in the middle of page's server-side life-cycle. This question has to be asked client-side and user's response has to come to the server as part of the page's submitted data.
All ScriptManager.RegisterStartupScript does is contributes to the final html content that will be sent to the client when the page completes request processing. Keep in mind that by the time this html content arrives to client computer the user may have closed the browser and gone home.
Use AJAX to submit query to server and make the server code so that it does it’s processing in two parts. I don’t have any working examples of this but this is how it would work in general. For posting data to server you can use native AJAX objects in JS or any other library as others suggested and for processing data on the server side you can use generic handlers (ashx) instead of standard web pages.
Send request to the server.
Catch the first part of the processing via JS on the client page.
Show JS window
Submit the other part to server
You’ll have to send results of the first part of processing back to the client because server will not be able to connect second request with the first one by default.

HTML Javascript Modal Popup Window with Auto Close

The main idea is to replicate what we see on the Banks or American Express sites, where a MODAL Popup appears to they tell us that the session "is going" to expire.
To this, I wanted to add an "Auto-Close" Popup event that will happen after XX seconds and then I will want to call a button event Onclick to "auto save" the current work, before redirecting the user to the Logout page.
So mainly I would like to know what's the best way to do the following:
1) Display a MODAL Message after let's say 1 minute (for testing purposes). This could be a DIV appearing on top of the current page, or a Dialog Message Box both MODAL.
2) Display a message and also a Reverse Timer, something like "Please save your work before the session expires"
3) Auto Close (or hide) that Message dialog after XX seconds
4) Call a button onclick event.
BackEnd is ASP.NET using C#
Something like this will get you started:
setTimeout(WarnTheUser,10000);//fires after 10 seconds
function WarnTheUser()
{
document.getElementById('warningDiv').innerHTML="<H1>This page will auto save in 1 minute</H1>"; //or whatever
setTimeout(saveData,60000);
}
function saveData()
{
form.submit();//adjust accordingly
}
jsfiddle.

Client-Side validation prvent Manually Postback by JavaScript eval()

I encouter some postback issue when using GetPostBackEventReference. Here is the Scenario:
I have a javascript modal popup dialog and got a button in this modal dialog which used to select things (this is NOT an asp:button control)
When this javascript dialog HTML button is clicked, it will call the MS AJAX web service call by the javascript: eval() method. And this MS AJAX web service call is dynamically generated. So the code is like this:
var serviceCall = svcCall + "(" + parameters + ")"; //dynamically generate the MS AJAX web service call here
eval(serviceCall);
//use eval to trigger the MS AJAX web service call
As you may all know, after complete the MS AJAX web service, you can define a callback function to handle the completion:
function OnComplete(result, userContext, methodName) {
//force to call postback manually
eval($(userContext[0]).val());
//close the javascript dialog here
}
As I have mentioned before, the MS AJAX web service call is built dynamically, and when the MS AJAX web service call is construct, it will be passing a userContext which contain the postback value (i.e. "__doPostBack('ctl00$ContentPlaceHolder1$btnSelectUser','')", so when the javascript eval() is called, it simulate a asp:button click postback.
The userContext[0] basically holding a asp:hidden field's ClientID, and the hidden field's value is set during the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
btnSelectUser.ValidationGroup = "popupSelect";
btnSelectUser.CausesValidation = false;
this.hdnBtnPostback.Value = Page.ClientScript.GetPostBackEventReference(btnSelectUser, string.Empty, false);
}
As you can see, this is how I bound the asp:button (i.e. btnSelectUser) 's Click Event to the asp:hiddenfield using the GetPostBackEventReference, and set the registerForEventValidation argument to false. I have also tried to use different ValidationGroup and set the CausesValidation to false, but no hope. :(
In summarize, I bound the asp:button's Click PostBackEventReference(i.e. __doPostback(....)) to the asp:hidden field's Value attribute, and using javascript eval() to eval this hidden field's value in order to manually trigger postback.
p.s. the btnSelectUser is an asp:button control and used to call out the javascript modal dialog.
Ok, here is the Problem:
In the same page, there is some asp:validator, e.g. and , and of coz, when the page run into error, this validator and callout will display to the user. e.g. When the user didn't fill in anything and submit the form, the ValidatorCalloutExtender will display a ballon and tell the user. Imagine one of this ballon/validatorCalloutExtender come out and on top of your screen at the moment.
Then you click the btnSelectUser (asp:button) to show the javascript modal dialog, and in the dialog, you Add some users, and once you hit the SELECT button inside this modal dialog, a MS AJAX web service is trigger as mentioned above, and once this web service is complete, it eval() the asp:hidden field's value (i.e. __doPostback(...))......and do the postback manually.
However, because of the validatorCalloutExtender ballon has display, it somehow cannot trigger the postback in this way, but when I close the ballon/validatorCalloutExtender, the manual postback using eval() is just working fine. Even more strange is that, when the ballon is displayed, the first time I click the SELECT button inside this modal dialog it doesn't fire the postback, however, if I do the same thing again (i.e. open up the javascript dialog, and choose some users, then click the SELECT button again). It able to do the manual postback....and I don't understand why the first time doesn't work.
This has really drive me crazy, hope anyone here can help, would be really appreciate. Thank you so much folks. :)
Have a nice day. Looking to heard from you all shortly.
When you call __doPostBack(eventTarget, eventArgument) a form submission is triggered:
This from post will proceed if WebForm_OnSubmit(); return true.
WebForm_OnSubmit result depends on ValidatorOnSubmit result, which in turn depends on
ValidatorCommonOnSubmit result if Page_ValidationActive == true.
Now if you are still with me, as in the function below:
function ValidatorCommonOnSubmit() {
Page_InvalidControlToBeFocused = null;
var result = !Page_BlockSubmit;
if ((typeof(window.event) != "undefined") && (window.event != null)) {
window.event.returnValue = result;
}
Page_BlockSubmit = false;
return result;
}
The result of ValidatorCommonOnSubmit depends on Page_BlockSubmit, so the only thing to block your postback is Page_BlockSubmit == true, it has nothing to do with validation callouts.
I was unable to simulate your case, but if you could post a full code sample it will help me track down the issue.

Categories