Adding a second endRequestHandler in a .NET web application - c#

I'm a newbie in C# language and I'm quite lost trying to extend an already existent and non-mantained .NET web application.
The application has a Web User Control with a button that, when clicked, refreshes its inner content through this piece of JavaScript code within the .ascx:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender, args) {
var btnId = '<%= btn.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnId) {
// loads a popup with the new content
}
}
This works perfectly. The problem comes when I try to add a new Web User Control which does practically the same, but of course through a different button and loading different content. I replicated the code structure, both in the front and in the back, but I cannot get the second endRequestHandler to execute:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandlerStats);
function endRequestHandlerStats(sender, args) {
alert("I'm here!");
var btnStatsId = '<%= btnStats.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnStatsId) {
// loads another popup
}
}
Suprisingly, that alert pops when the first btn is clicked, but not with the second btnStats.
I think the problem is caused because the btnStats doesn't trigger a request, but as I said I am new at this and I have no idea why. And the operation is done properly, the only thing that doesn't work is what is done in that script. Any hints, please?

I believe that is what the if condition is for - it is to check which button was clicked. The event model of JavaScript doesn't allow multiple handlers to be attached (at least not without some extra work), so this is probably the next best thing.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender, args) {
var btnId = '<%= btn.ClientID %>'
var btnStatsId = '<%= btnStats.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnId) {
// loads a popup with the new content
}
else if (sender._postBackSettings.sourceElement.id == btnStatsId) {
// loads another popup
}
}

Related

Enter Does Not Work For Submit, ASP.NET Page Refreshes and Doesn't Search

I am working with an ASP.NET site with a C# back end. There is a .Master page where the tag is, and other search pages on the site will search when you hit enter after filling out the form. However we have one page that has a few text boxes and when you hit enter to search, it appears to just refresh and reload the page without searching. In order to search you have to hit the search button (which is an igtxt:WebImageButton ). All of the solutions I have found to this issue so far involve people using javascript to call some kind of function on submit. As far as I know there is no javascript being called when you hit the search button, it is all in the C# code. Once again I find myself searching SO and other sites for an answer but none of the solutions seem to fit my situation. The form tag is as follows:
<form id="form1" runat="server">
The web image buttons call a btn_SearchClick function that runs the search code. But since the form is started in the .Master file I can't edit that as it would effect all other pages as well. Is there any way to have enter call the btn_SearchClick from the form without having to put it in the form tag? I'm not sure what would've changed to cause this behavior on one page and none of the others.
if (!IsPostBack)
{
TextBox1.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
or u can use default button.it's work while cursor's in this box
protected void Page_Load(object sender, EventArgs e)
{
this.Form.DefaultButton = this.btnSubmit.UniqueID;
}
Add some jquery to control the Enter key behavior on your textbox. Something like this:
$(function() {
$('#<%=txtTextbox.ClientID%>').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
$('#<%=btn_SearchClick.ClientID%>').click();
}
});
});

How to create progress update control programatically in c# non visual web part in Sharepoint

How can I create progress update control programmatically in a c# non visual web part in Sharepoint?
I am using c# and the goal is to creates a text of "Loading..." inside the ProgressUpdate control that becomes visible while the update panel is loading more content and then disappears when content is loaded. If anyone can help that would be awesome. I tried the following, but no luck. A button triggers the update panel and the update works well, but when I try to add an update progress it gets added into the page, but it never appears when I click my button that triggers the update.
UpdatePanel up = new UpdatePanel();
up.UpdateMode = UpdatePanelUpdateMode.Always;
up.ID = "Panel1";
UpdateProgress upp1 = new UpdateProgress();
upp1.AssociatedUpdatePanelID = up.ID.ToString();
upp1.ID = "UpdateProgress1";
upp1.Controls.Add(new LiteralControl("<p>Loading...</p>"));
Controls.Add(upp1);
Alright so here is what I have found. If you make an Update Progress control outside an Update Panel, then it will fail to be able to listen to the trigger on the update panel when it fires. More can be read about that at the link below.
http://www.mostlydevelopers.com/blog/post/2008/08/23/Show-UpdateProgress-when-using-an-UpdatePanel-with-Triggers.aspx
So since I'm doing it this way, I had to use a javascript work around. I had to use the getInstance() method of the PageRequestManager object to get the instance of the PageRequestManager class. I then added the functions for the asynchronous request when it is initialized and ends. This will allow us to show our UpdateProgress control when an Asynchronous call begins and ends. (See Javascript Below)
//Function for postbackUpdateProgress
var prm = Sys.WebForms.PageRequestManager.getInstance();
var postBackElement;
function CancelAsyncPostBack() {
if (prm.get_isInAsyncPostBack()) {
prm.abortPostBack();
}
}
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
if (prm.get_isInAsyncPostBack()) {
args.set_cancel(true);
}
//Get the element that asynchronous postback
postBackElement = args.get_postBackElement();
//check to see if any of the following controls activate sender request.
//search is used to search for the ID name in the string that sharepoint spits out
// as the ID.
var controlA = postBackElement.id.search("DropDownListType");
var controlB = postBackElement.id.search("UserProfileDropList");
var controlC = postBackElement.id.search("MoreNewsLinkButton");
var controlD = postBackElement.id.search("PreviousNewsLinkButton");
if (controlA != -1 || controlB != -1 || controlC != -1 || controlD != -1) {
$('*[id*=Panel1]:visible').hide();
//show UpdateProgress
$('*[id*=UpdateProgress1]').show();
}
}
//After async postback complete, then show panel again and hide UpdateProgress
function EndRequest(sender, args) {
$('*[id*=Panel1]').show();//use wild card in jquery to find Panel1 ID
$('*[id*=UpdateProgress1]:visible').hide();
}
Please note that I had to do a search() for the ID name because sharepoint puts a bunch of text before your ID name and javascript would otherwise not be able to find it by the text literal of the ID alone. A wild card approach with jquery is used to find the panel by using:
$('[id=Panel1]').show();//use wild card in jquery to find Panel1 ID
to show it.
and
$('[id=Panel1]:visible').hide();
to hide the update panel when the async call is initialized. You don't have to hide the update panel, but my particular implementation looks more aesthetically pleasing if I do.

How to unregister Page.ClientScript in C# Asp.net

I am registering java script to my Asp.net code behind file, which is working fine. Now, I have some update panels on the same page and problem is whenever there is any change in any of the update panel, this script is automatically getting called. Is there any way that I can stop this happening. I can't remove update panels from my page and this script is also a very essential part of the application. In this situation I am just calling a alert (rad alert with set time out functionality) when Save Button is clicked or an Update routine is called while I have few other buttons in update panels and whenver any of the button which is registered to the update panels clicked, the following script is called un-willingly. Anyone's help will really be appreciated.
following is my Page.ClientScript
string radalertscript = "<script language='javascript'> Sys.Application.add_load(function(sender, e) {var oWnd = radalert('dialogMessage', 400, 140, 'Saved');window.setTimeout(function () { oWnd.Close(); }, 3000);});</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);
You can assign empty string to same key radalert to remove the script.
if(some_condition)
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", "");
Edit: Based on comments, you can make it simple without using RegisterStartupScript
In code behind
btnSave.Attributes.Add("", "saveButtonFunction();");
In Javascript
<script language='javascript'>
Sys.Application.add_load(function(sender, e) {
if(btnSaveClicked){
var oWnd = radalert('dialogMessage', 400,140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
btnSaveClicked = false;
}
});
btnSaveClicked = false;
function saveButtonFunction(){
btnSaveClicked = true;
};
</script>
Thank you very much for your answer Adil. I already have followed the same approach with little difference. I have taken JavaScript out from my code behind file and have registered Sys.Application.add_load event as follow
Sys.Application.add_load(DisplayRadAlertHandler);
function DisplayRadAlertHandler() {
var getMessage = document.getElementById('<%=radAlertDialogHidden.ClientID%>').value;
if (getMessage != "") {
document.getElementById('<%=radAlertDialogHidden.ClientID%>').value = "";
var oWnd = radalert(getMessage, 400, 140, 'Saved');
window.setTimeout(function () { oWnd.Close(); }, 3000);
}
}
Here I am setting my alert message in a hidden input field from code behind file and in the above event handler I am just checking if message is there than reset the hidden field and display the message. Your approach is also right and I have marked your answer but as I am displaying my message from multiple locations (Save button, Update routine etc.) so by assigning value to hidden input field and than resetting in above event handler looks more appropriate. Thanks once again for your help.

Using Jquery to prevent a "Submit Button" from posting data if a field is left blank

So I'm putting together a little registration area for my web project, here. The user inputs various strings such as "Username", "Password", etc.
I already have a bit of code set up in order to prevent duplicate Usernames or Passwords in the database. I also have a guard in place if the "Password" and "Repeat Password" fields don't match.
What I'm trying to do now is to -
1: If the user attempts to Submit data while a field is blank, it will not post.
2: Display a "Fields cannot be blank" div I've assigned "display: none" to.
I was thinking something along the lines of assigning the input fields a class of "Required", and using some sort of code such as
if == null
.show;
return false; //To prevent the rest of the function (the submit button posting to login/register) from firing.
Running into obscene problems. Anyway. Here's what I have so far.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
});
Any thoughts? At first I thought that I literally -cannot- use "class" to mark an input field, and then have that input field compared to a null value. I don't know, though.
You should use the .submit() jquery event handler on the form instead of .click() on the button. Then return false to prevent the normal form submission if needed.
Since you are trying to submit the form using $.post you should stop the default behavior of the form submit by alwasy returning false from submit button click handler.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
return false;
});
The jQuery way of preventing form submission is to use preventDefault(), like:
$("#SubmitButton").click(function (event) { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
event.preventDefault(); //And nothing else fires
return;
}
//...
});
However, since you are posting the form asynchronously when validation passes, what you really want is something more along the lines of:
$("#SubmitButton").click(function (event) { //Click Submit
event.preventDefault(); //we don't ever want to allow the default behavior
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
});
The rest of what you suggest (using a class to mark each required input field, checking them all for empty strings) is reasonable.
Be aware that because you are binding the button's click event instead of the form's submit event it is entirely possible for the user to submit your form without ever clicking on your button and triggering your validation code. For instance, by pressing return from any one of your text fields.
Also note that in this case you may find it more convenient to just use a traditional onsubmit directive on the form, like:
<form onsubmit="validateAndPost(); return false;">
<!-- inputs and buttons, etc. -->
</form>
<script>
function validateAndPost() {
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
}
</script>
Example: http://jsfiddle.net/AwxGE/
I admire your desire to use jquery, however I would advise using a normal ASP.NET ReqiredFieldValidator control. As well as making your page substantially more concise and easy to maintain, it also allows you to very simply invoke server-side validation:
public void submitbutton_click(object sender, EventArgs args){
Page.Validate();
if(Page.IsValid){
doStuff();
}
}
Please don't reinvent the wheel, and don't trust the browser to behave as you think it will.
use this -
$(document).on('click', '#SubmitButton', function () {
`enter code here`
});

jquery click tracking is acting a little strage

On some links on my HTML page I have a special CSS class, that when clicked, I make a ajax call to a click.aspx page and track the click.
blah-1
$(".click").bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
So what is happening is the value of source, after clicking a few links (that open in a new window) becomes:
source=blah1
then it becomes
source=blah1,blah2
Maybe you need to change it to:
$(".click")each(function(i) {
$(this).bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
});
so that each is processed separately...

Categories