Page:
<body>
<form id="frmLogin" runat="server">
<asp:Button ID="btnClick" OnClientClick="openConfirmDialog();" OnClick="PopulateLabel" runat="server"/>
<div id="divDialog"></div>
<asp:Label ID="lblText" runat="server"></asp:Label>
</form>
</body>
JS
<script type="text/javascript">
$(document).ready(function() {
$("#divDialog").dialog({autoOpen: false,
buttons: { "Ok": function()
{
$(this).dialog("close");
},
"Cancel": function()
{
$(this).dialog("close");
}
}
});
});
function openConfirmDialog()
{
$("#divDialog").dialog("open");
}
C#
protected void Page_Load(object sender, EventArgs e)
{
lblText.Text = "";
}
protected void PopulateLabel(object sender, EventArgs e)
{
lblText.Text = "Hello";
}
This code opens me a dialog box with Ok and Cancel button but it do not wait for user activity and post the page immediately and the label gets populated. I need to call the c# function based on user activity. If user clicks "Ok" label should get populated and if user clicks "Cancel" it should not call the c# function. How do I achieve this?
First, to prevent the page from immediately posting back to the server, you need to cancel the default behavior of the click event by returning false from your handler:
<asp:Button ID="btnClick" runat="server" OnClick="PopulateLabel"
OnClientClick="openConfirmDialog(); return false;" />
Next, you need to perform the postback yourself when your Ok button is clicked:
$("#divDialog").dialog({
autoOpen: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
__doPostBack("btnClick", "");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
Note that the first argument to __doPostBack() is the name of the control (its UniqueID in ASP.NET terminology). Since the button is a direct child of the <form> element, we can hardcode its id in the __doPostBack() call, but things will get more complicated if it resides in a container hierarchy. In that case, you can use ClientScript.GetPostBackEventReference() to generate the appropriate call to __doPostBack().
EDIT: Since your page does not contain any postback-enabled control, __doPostBack() won't be defined on the client side. To work around that problem, you can use a LinkButton control instead of a Button control.
Added another button and used the jQuery click() event to trigger new button's click event which will in turn trigger the respective event handler in C#
Related
I have the following ItemTemplate in my GridView:
<ItemTemplate>
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnClientClick="myfunction(); return false;" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
</ItemTemplate>
For the ItemTemplate I have a button which opens a popup window when clicked by using the following JQuery:
$(document).ready(function () {
$(".btnSearch").click(function (e) {
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
function myfunction() {
}
my Command code-behind:
protected void btnShow_Command(object sender, CommandEventArgs e)
{
int index = 0;
if (e.CommandName == "ViewAll")
{
index = Convert.ToInt32(e.CommandArgument);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
//tbGL.Text = html;
//upData.Update();
//MessageBox.Show(index.ToString());
}
}
I added the OnClientClick="myfunction(); return false;" because it was doing a postback each time I clicked. If I have multiple rows, it only works the first time I click but any time after, the popup is not displayed when another or the same button is clicked.
How do I resolve it so no matter which button is clicked the popup is displayed without doing a postback?
Actually you have not showed up the implementation of your method myfunction(), in case the myfunction() method have any syntactical error then the OnClientClick event will be void and it will post-back/submit the form to the server.
Try to remove the call from OnClientClick and just implement your logic at jquery on click event by using class selector as follows
$(document).ready(function () {
$(".btnSearch").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked"); // you can put your method mymethod() here
// you can put youe popup logic here
return false;
});
});
You can also see this example of js fiddle
Put it out on the tag or <%: Html.BeginForm %> tag
OnClientClick="return myfunction();
function myfunction(){
// you can put youe popup logic here
return false;
}
Using like this your button never do post back.
I have a JS function (Show alert box), and have a link button in ASP page, On click event from code behind for this link button I want to call this function and then redirect to certain page.
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
Response.Redirect("myPage.aspx");
}
Here when I click on the link button, it simply don't display the alert box/window and redirect to the page.
You should use LinkButton.ClientClick instead of LinkButton.Click event.
Click event is handled on server. When user clicks the button, page is posted back to server and code is executed on server side.
ClientClick event is really a name of JavaScript function which should be executed.
You should probably do something like this:
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClientClick="showMyAlertAndSubmit()"></asp:LinkButton>
<script type="text/javascript">
function showMyAlertAndSubmit(){
alert("Your password is being changed");
// submit your form
}
</script>
Why your current code doesn't work
You currently send script for showing a message, and redirect at the same time. This means that browser receives instructions to show a message and to redirect, and it redirects the user before showing the message. One approach could be to redirect from client side. For example:
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
and on client side
function myFunction() {
// show your message here
// do other things you need
// and then redirect here. Don't redirect from server side with Response.Redirect
window.location = "http://myserver/myPage.aspx";
}
Other options
Since you need to first perform checks on server side before saving data and redirecting, you can use ajax to call server without performing postback.
Remove Click handler, and only use ClientClick:
function myFunction() {
$.ajax({
type: "POST",
url: "myPage.aspx/MyCheckMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ShowAlert();
window.location = "http://myserver/mypage.aspx";
}
});
}
For more details please check this tutorial.
Change your code like this:
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" OnClientClick="myFunction()" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
Response.Redirect("myPage.aspx");
}
Change your javascript function to :
<script type="text/javascript" language="javascript">
function myFunction() {
// alert will stop js execution
alert("document is ready!");
// then reload your page
__doPostBack('pagename','parameter');
}
</script>
And call it from code-behind with this function :
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
//do your job here
//then call your js function
ScriptManager.RegisterStartupScript(this,this.GetType(), "CallMyFunction", "myFunction();", true);
}
What you're missing is waiting for JavaScript alert dialog to popup and then redirect to the page.
In order to do this you need to tell button to wait for JavaScript alert dialog to popup and then do the Server side work after.
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function alertBeforeSubmit() {
return alert('Document Ready');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="Do" runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="return alertBeforeSubmit();" />
</div>
</form>
</body>
CS:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
Good day,
I have a aspx contain a button with ID button1, the following is my aspx code :
<div>
<asp:LinkButton ID="lnkView" CommandName="VIEW" runat="server">View</asp:LinkButton>
<asp:Button ID="button1" runat="server" Text="OK" onclick="button1_Click" />
</div>
/*
some code here
*/
<script>
function test()
{
document.getElementById("<%=button1.ClientID %>").click();
alert("hello");
return true;
}
</script>
The following is my aspx code behind:
//some code here
lnkView.Attributes.Add("onclick", "return test()");
//some code here
protected void button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Javascript", "<script>alert('Record Added Successfully')</script>", false);
}
As you can see, my linkView link button have a javascript function test() when click on it.
I can alert the "Record Added Successfully" by click on the Button1.
However, when I click on linkView link button, the "Record Added Successfully" didnt alert, it only alert "Hello".
I think I am missunderstand in some programming concept.
Kindly advise.
Thanks.
This will trigger the event in code behind.
Try this in your .aspx page:
//Code:
<script type="text/javascript">
function test(parameter)
{
__doPostBack('button1_Click', parameter)
}
</script>
You can fix this by returning false instead of true as the result of the function test(). This way you will cancel default behavior of the link with ID lnkView ie sending form
I used an event listener to prevent the action of my asp:button (submit) because I wanted to validate my form with a javascript function before it actually gets submitted.
formInstance.addEventListener('submit', function (event) {
event.preventDefault();
}, false);
Here is the button:
<asp:Button ID="btnCreateForm" CssClass="submit-form button" runat="server"
Text="Save Form" OnClick="btnCreateForm_Click"
OnClientClick="Sharpforms.checkFormEntry()" />
The fired javascript:
checkFormEntry: function () {
var formName = document.getElementById("txtFormName");
if (formName.value.trim() == "") {
alert("Please fill in a valid form name!");
return false;
}
else {
//formInstance.submit();
return true;
}
}
Apparently the javascript submit() does submit the form because the page is being reloaded but I recognized that it doesn't enter my ASP side btnCreateForm_Click function any more:
protected void btnCreateForm_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Test if the button has been clicked.");
}
When commenting my form event listener as well as the submit() and try to submit it natively he enters the click function without problems. But then I have no possibility to check my form on the client side. What am I missing?
You have to add return to the OnClientClick event. If the function returns true, the postback occurs. If the function returns false, the postback gets cancelled.
<asp:Button ID="btnCreateForm" CssClass="submit-form button" runat="server"
Text="Save Form" OnClick="btnCreateForm_Click"
OnClientClick="return Sharpforms.checkFormEntry()" />
Also, doing it in this way you can remove the event listener.
This is a simplified version of what I want to do. Basically I have a datalist with a bunch of stuff in it and when you mouseover items in the datalist I want jquery to hide/show stuff. The problem is that after I databind my gridview/repeater/datalist jquery quits working if the gridview/repeater/datalist is in an update panel.
After you click the button in the sample below, the jquery that makes the span show up when you mouse over quits working.
Any ideas of why this is happening, how to fix it or a better way to do this?
<script type="text/javascript">
$(document).ready(function() {
$('.comment-div').mouseenter(function() {
jQuery("span[class=mouse-hide]", this).fadeIn(50);
});
$('.comment-div').mouseleave(function() {
jQuery("span[class=mouse-hide]", this).fadeOut(50);
});
});
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="comment-div">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<span class="mouse-hide" style="display: none;">sdfgsdfgsdfgsdfg</span>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStuff();
}
}
public void BindStuff()
{
TestDB db = new TestDB();
var x = from p in db.TestFiles
select new { p.filename};
x = x.Take(20);
GridView1.DataSource = x;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
BindStuff();
}
The reason this is happening is because the controls get recreated on a partial postback. Use the 'live' feature of jQuery so rewrite your code like:
$(document).ready(function() {
$('.comment-div').live('mouseenter',function() {
jQuery("span[class=mouse-hide]", this).fadeIn(50);
});
$('.comment-div').live('mouseleave', function() {
jQuery("span[class=mouse-hide]", this).fadeOut(50);
});
});
When the UpdatePanel refreshes, it completely replaces all of the DOM elements that you had previously attached event handlers to. The easiest fix is to initialize your event handlers in pageLoad() instead of $(document).ready(). Its code will be executed both on the initial page load, but also after every UpdatePanel refresh.
The better solution is to change your code to use live() or delegate(), so that the event handlers aren't impacted by periodic changes in the page's contents.
When you do a AJAX postback using an update panel the DOM within it's removed and re-created when the AJAX response arrive.
The handlers you attached are lost unless you use the live method or the livequery library
See below for different jQuery versions:
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+