i am using < div onclick="""> to call the server side .How can i avoid full page refresh when user click the < div>?
Here is my coding.
HTML
<asp:UpdatePanel ID="updatePanel1" runat="server"> <ContentTemplate>
<div id ="cde" runat="server" style="background-color: #00FFFF" > </div>
<asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label>
</ContentTemplate> </asp:UpdatePanel>
Server side
protected void Page_Load(object sender, EventArgs e)
{
//--Register for div onclick function --
cde.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "divMember_Click");
//**Register for div onclick function**
}
protected void divMember_Click()
{
this.Label1.Text = System.DateTime.Now.ToString();
}
public void RaisePostBackEvent(string eventArgument)
{
if (!string.IsNullOrEmpty(eventArgument))
{
if (eventArgument == "divMember_Click")
{
divMember_Click();
}
}
}
I try putting the label within the update panel . But postback will still occur. How can i refresh the label without full page reload?
you can use Jquery .ajax function or pagemethod.YourWebMethod.
Create Web Method in your C# Code and call it using these two functions.
You can do Page Method by EnabledPageMethod="true" in script Manager and use Jquery .ajax function put jquery java script.
This will be on page behind code (create Web Method):
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
As referenced in Default.aspx, this is java script:
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
<head>
<title>Calling a page method with jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="Default.js"></script>
</head>
<body>
<div id="Result">Click here for the time.</div>
</body>
Put the div and Label into UpdatePanel
Try this way,
Keep your label in the Update Panel id"Updatepanel1" with following properties
Update Mode : Conditional
EnableViewState : true(if you are using it)
You need to have an asp:ScriptManager present on your page to use UpdatePanel. See here.
Related
I'm trying to change a label text from cs file after I receive a message from the server.
I tried using to put the label in updatepanel but couldn't make it work.
How can i update the display of the label?
Usually this is something along the lines of
myLabel.Text = "Value";
If it's in an UpdatePanel, the rules are a little different. I think you need to get the control, then update its value. Something along the lines of:
Label lbl = (Label) updatePanel1.FindControl("myLabel");
lbl.Text = "Value";
If you are trying to avoid a post back, then you can use ASP.NET AJAX Page Methods to query the server via AJAX and then push the value returned into the label control, like this:
Markup:
<script type="text/javascript">
$(document).ready(function () {
$('.TheButton').click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.TheLabel').text(data.d);
}
});
return false;
});
});
</script>
<asp:Label ID="Label1" runat="server" Text="Nothing" CssClass="TheLabel" />
<br/>
<asp:Button runat="server" ID="Button1" CssClass="TheButton" Text="Update Label"/>
Code-behind:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
Note: ASP.NET AJAX Page Methods are static methods that are not part of the ASP.NET page life-cycle. They do not have access to any of the controls on the page, but are very useful for getting data from the server (in this case the server time). In the interest of simplicity, I used CSS class names on the server controls to make the jQuery selectors simpler.
I have a ScriptManager which is added to my MasterPage;
<telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnablePageMethods="true" />
I have a Web User Control which is placed on the master page.
Inside the web user control, I'd like to use PageMethods but it complains that PageMethods is not defined.
function ddlSqlConnections_SelectedIndexChange(selectedValue) {
PageMethods.OnSelectedIndexChanged(selectedValue);
location.reload(true);
}
I added a new ScriptManager to the user control and it complained that only one scriptmanager can exist on one page so
basically how to add a reference to the master page script manager, from the user control?
It doesn't seem to be possible?
Thanks,
Use a regular ScriptManager instead of the RadScriptManager:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
My conclusion was it's not possible with a Web User Control Page Method and I used AJAX with web service instead:
$('.ddlSqlConnections').change(function (control) {
var selectedValue = control.currentTarget.value;
if (selectedValue == 0) {
return;
}
$.ajax({
type: "POST",
url: "AdminService.asmx/AdminConnectionsOnSelectedIndexChanged",
data: "{uniqueName: " + selectedValue + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
location.reload(true);
},
error: function (msg) {
alert('failed to send a web service request; please contact the administrator.')
}
});
});
You could try to Invoke a method in your masterpage from your userconrol.
Page.GetType().InvokeMember("MethodName", BindingFlags.InvokeMethod, null, this.Page, new object[] { });
Is there a way to change the values for these two attributes on the client side and have it reflected on the server side after the postback. I tried it but it does not seem to work. I wanted to have one button on the page that I would delegate submits too, and assign these two arguments on the client side. Seems like not possible. Any idea?
Assuming there is a button named "cmd" in the form
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
});
});
</script>
If one checks the value after postback they are still the same as they were before postback.
I tried you're code and it works fine.
Just make sure you're button is not generating a postback by adding OnClientClick="return false;":
<asp:Button ID="cmd" runat="server" Text="Button" OnClientClick="return false;"></asp:Button>
Also you won't see the difference in "view source" on your browser. But the change has been made in the DOM. Use firebug and add the console.log to see for yourself:
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
console.log(this);
});
The console.log(this) gave me the following:
EDIT:
If you think about it. If the button creates a postback, then the button will reset itself to normal once the page loads again.
EDIT #2:
I don't need the change on the client
side, I need it on the server side.
That was the whole point of the
question. I need to see the change on
the server side, and it does not seem
to be possible. – epitka
Okay... Well, in that case. It is not possible. "CommandArgument" and "CommandName" means nothing to the client and is not accessible.
However there are work arounds. But depending on the context of your application they might not be useful to you.
You could try using your own attributes like the answer suggested here.
Or you could execute the __doPostBack on the client side and pick up the __EVENTARGUMENT on the code behind.
(The link button is there to generate the __doPostBack function by asp.net.)
Like such:
<script type="text/javascript" language="javascript">
function DoPostBack() {
__doPostBack('cmd', 'thesearemyarguments');
}
</script>
Page:
<asp:Button ID="cmd" runat="server" Text="Button"
OnClientClick="DoPostBack(); return true;"
onclick="cmd_Click" ></asp:Button>
<asp:LinkButton ID="LinkButton1" runat="server" Visible="false">LinkButton</asp:LinkButton>
Code Behind:
protected void cmd_Click(object sender, EventArgs e)
{
Response.Write(Request.Params["__EVENTARGUMENT"]);
}
I was having the same problem here, I found the solution was to use an ajax call to send my buttons id to a function where i can set it as a session variable. Because the asp control I wanted to update could not be accessed from within a static call. On success of the ajax call I click a hidden button which uses a non static click event to manipulate the session variable i set and update the control
My links were generated within a repeater, and they correspond to different rooms of a house. When you click on the link there is another repeater that has to update to show products that are sold which are relevant to the room of the house that was clicked on
my link that is generated from the repeater
<%#Eval("DocumentName") %>
my client side method
$('.changeroom').each(function () {
$(this).on('click', function () {
var id = $(this).attr('data-id');
var object = { 'sender': id };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/App/Page Templates/FindByRoom.aspx/UpdateRoomID",
data: JSON.stringify(object),
success: function() {
$('#btnID').click();
}
});
});
});
btnID is a simple aspButton with a server side click event
and finally my server side methods
protected void btnChangeRoom_OnClick(object sender, CommandEventArgs e)
{
int id = 0;
if (Session["RoomID"] == null) return;
Int32.TryParse(Session["RoomID"].ToString(), out id);
if (id == 0) return;
//do something with your buttons id
//i updated the path of a repeater and reloaded the data
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void UpdateRoomID(string sender)
{
HttpContext.Current.Session["RoomID"] = sender;
}
I have a asp.net app that I want to disable the buttons as soon as they are clicked in order to prevent multiple submissions. I'd like to use jquery for this as the site already liberally uses it anyway.
What I've tried is:
$(document).ready(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
})
});
The above will disable the button, and the page submits, but the asp.net button on click handler is never called. Simply removing the above and the buttons work as normal.
Is there a better way? Or, rather, what am I doing wrong?
UPDATE
Okay, I finally had a little time to put a very simple page together.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SubTest.aspx.cs" Inherits="MyTesting.SubTest" %>
<!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 src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button 2" />
</div>
</form>
</body>
</html>
The code behind looks like:
using System;
namespace MyTesting {
public partial class SubTest : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// this will execute when any button is pressed
Response.Write("postback");
}
}
protected void Button1_Click(object sender, EventArgs e) {
// never executes
System.Threading.Thread.Sleep(1000);
Response.Write("Button 1 clicked<br />");
} // method::Button1_Click
protected void Button2_Click(object sender, EventArgs e) {
// never executes
System.Threading.Thread.Sleep(1000);
Response.Write("Button 2 clicked<br />");
} // method::Button2_Click
}
}
When you click on a button it obviously disables the buttons, but NEITHER of the button clicks are run.
Rendered HTML
<!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>
</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {
$('input[type=submit]', $(this)).attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<form name="form1" method="post" action="SubTest.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTcxODU4OTc0MWRkParC5rVFUblFs8AkhNMEtFAWlU4=" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKB57WhCAKM54rGBgK7q7GGCC6LlWKFoij9FIBVuI0HOVju/fTy" />
</div>
<div>
<input type="submit" name="Button1" value="Button" id="Button1" />
<input type="submit" name="Button2" value="Button 2" id="Button2" />
</div>
</form>
</body>
</html>
You can do it a slightly different way, like this:
$(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]').click(function() { return false; });
});
});
What this does is makes future clicks ineffective, basically making them do nothing. When you disable an input, it also removes the key/value pair from being submitted with the <form>, so your server-side action which is triggered by it doesn't work.
It's worth noting, in jQuery 1.4.3 you'll be able to shorten this down to:
$(function () {
$("#aspnetForm").submit(function () {
$('input[type=submit]').click(false);
});
});
The approach of disabling the button before the submit has two effects: -
a) The button takes on the disabled appearance.
b) The button's value is not posted in the form parameters.
If the button's value is not being posted to the server, ASP.Net does not know which button was pressed and thus it does not run the relevent OnClick handler.
To verify add the following to your code behind
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Load " + IsPostBack + "<br />");
foreach (string s in Request.Form.AllKeys)
{
Response.Write(string.Format("s:'{0}' = {1}<br />", s, Request.Form[s]));
}
}
And then run the page (both with J.S. to disable the buttons and without).
If the button's value is not being posted to the server, ASP.Net does not know which button was pressed and thus it does not run the relevent OnClick handler.
Just another observation. Alternatively, you can lock UI with a nice overlay busy message.
The Mark-up part:
$(function() { // when document has loaded
($.unblockUI); //unlock UI
//Show busy message on click event and disable UI
$('#btnHelloWorld').click(function() {
$.blockUI({ message: '<h4><img src="busy.gif" />Please wait...</h4>' });
});
});
<asp:Button ID="btnHelloWorld" runat="server" Text="Hello World" /><br/>
The Code behind:
Protected Sub btnHelloWorld_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHelloWorld.Click
Label1.Text = "Hello World"
Threading.Thread.Sleep(5000)
End Sub
Check out jQuery BlockUI Plugin
I just wanted to add an additional resolution. We decided to just completely remove the button once it was clicked and replace it with some text.
To do this we did:
$(function () {
$(".DisableButton").click(function () {
$(this).hide();
$(this).after('<p>Please Wait. Retrieving information. This may take up to 60 seconds.</p>');
});
});
Note that this hides the button then injects some html after the buttons code. Hiding it allows .Net to go ahead and run the onclick handler during post back while removing it as a clickable thing on the screen.
Add this attribute to your button:
usesubmitbehavior="False"
This will insert something like the following into onclick:
javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$Main$Tabs$SaveTab$Cancel", "", true, "", "", false, false))
This code will cause a post back even if the button is disabled. Showing a confirmation dialog and allowing the post back to be cancelled gets a little more interesting:
var click = $("[id$='_Cancel']")[0].onclick;
$("[id$='_Cancel']")[0].onclick = null;
$("[id$='_Cancel']").bind('click', function (event) { addFeeSchedule.onCancelClick(event) });
$("[id$='_Cancel']").bind('click', click);
In order to prevent the post back from occurring immediately, remove the onclick code inserted by .net and bind it after your own function using jQuery. Use event.stopImmediatePropagation(), to prevent the post back:
onCancelClick: function (event) {
var confirmResponse;
confirmResponse = confirm('No fee schedule will be created.\n\nAre you sure you want to cancel?');
if (confirmResponse == true) {
showWait();
event.target.disabled = 'true';
} else {
event.stopImmediatePropagation();
}
},
The answer provided by Nick Craver is by far the best solution that I've found anywhere on the net. There is one situation, however, where the solution does not work well - when the form contains submit buttons within an UpdatePanel with it's UpdateMode property set to "Conditional" and/or ChildrenAsTriggers property set to false.
In these situations, the contents of the update panels are not automatically refreshed when the async postback has completed. So if these update panels contained any submit buttons then the given solution would effectively leave these buttons permanently disabled.
The following enhancement to the solution handles this problem by re-enabling the buttons after an async, or 'partial', postback:
var canProcessClicks = true;
if (typeof (Sys) != 'undefined') {
// handle partial-postback
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager .add_initializeRequest(function() {
// postback started
canProcessClicks = false;
});
requestManager .add_endRequest(function() {
// postback completed
canProcessClicks = true;
});
}
$(function () {
$('input[type=submit]').on("click", function () {
return canProcessClicks ;
});
$("#aspnetForm").submit(function () {
if (typeof (Sys) != 'undefined' && Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
// this is an async postback so ignore because this is already handled
} else {
// full postback started
canProcessClicks = false;
}
});
});
For this you have to use input button attribute disable all the controls
<script language="javascript" type="text/javascript">
function MyDisableFunction() {
alert(`Now You Postback Start`);
$(":input").attr("disabled", true);
return true;
}
</script>
Fore more detail check this link
I'm trying to call a static method in c# using jQuery Ajax. I've tried before but now it is not working. I get error status as 200 Ok. Here is my code:
$("#btnSample").live("click", function()
{
$.ajax({
type : "POST"
, data : {}
, url : "jQueryAjax.aspx/SampleMethod"
, contentType : "application/json; charset=utf-8"
, dataType : "json"
, success : function(msg)
{
alert("Success : "+msg);
}
, error : function(error)
{
$("#lblSample").text(error.status);
}
});
});
My Server-side code is:
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
aspx for Button:
<input type="button" id="btnSample" runat="server" value="Show What" />
I've recreated your code on my side.
<%# 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>
<script src="Js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#btnSample").live("click", function() {
$.ajax({
type: "POST"
, data: {}
, url: "Default.aspx/SampleMethod"
, contentType: "application/json; charset=utf-8"
, dataType: "json"
, success: function(msg) {
alert("Success : " + msg.d);
}
, error: function(error) {
$("#lblSample").text(error.status);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="lblSample"></asp:Label>
<input type="button" id="btnSample" runat="server" value="Show What" />
</form>
</body>
</html>
That's a copy and paste. I've tested it in IE8 and it works fine.
The one change I did make was changing your success output to use msg.d This is so it outputs Success : jQuery is Super. msg would NOT cause a crash - it would just output Success : [object Object] (msg is a object that contains a string called d which the return from the static method is called).
I haven't changed your static method at all
This is in my class (remember Default.aspx)
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
}
This is sitting inside my Default.aspx.cs file
I tried messing around to get a 200 OK error and the ONLY time I managed this was when I had
, contentType: "application/ json;charset=utf-8"
That has a space between the / and json.
But that isn't in your question. Maybe it is sitting in your code that way and you fixed it in the question?
One thing I see different about your script than the way I use it is wrapping the {} in the data part with quotes.
Try this:
, data: "{}"
Also,
This is a good article with some jquery ajax caveats:
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Your button is posting back instead of calling the click event. To stop the unintentional postback add e.preventDefault to your click handler. I'd also suggest not using a server side control (ie removing the runat=server) unless absolutely necessary. It just adds unneeded overhead.
I have the same problem too, but when i copy and paste the code into a new project it works fine. I think there should be something wrong with web.config