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.
Related
I am using Encosia's sample from his website on how to use ajax call
When I click on the div it's working fine and when I replace button instead of div it's refreshing the whole page and I don't find any errors in firebug.
Here is my code:
Script:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#getdate").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").html(msg.d);
}
});
});
});
</script>
HTML:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<div id="Result">Click here for the time.</div>
<button id="getdate" value="Click Me">ClickMe</button>
Code-behind:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
What most probably happens is - the button submits the page so the pages gets reloaded. I had this problem before in some browsers.
You need to specify type="button" attribute.
http://www.w3schools.com/tags/tag_button.asp
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[] { });
I want to update my dropdown list datasource (get the values from the database again) but i want to do that from jQuery, there i insert/update/delete records from that same database table.
This is my dropdown list
<asp:DropDownList ID="ddl" runat="server"
AppendDataBoundItems="True"
DataSourceID="ShortCodeDataSource"
DataTextField="ShortcodeId"
DataValueField="ShortcodeId">
<asp:ListItem>Select one...</asp:ListItem>
</asp:DropDownList>
<asp:ObjectDataSource ID="ShortCodeDataSource" runat="server"
SelectMethod="GetAllShortcodes"
TypeName="Sod.Iris.Service.ShortcodeService">
</asp:ObjectDataSource>
Also, beside code that a432511 posted, you can use UpdatePanel approach.
Put your dropdown in a UpdatePanel and then just call refresh from jquery.
On this link you have example how to do this:
http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/
cheers
You need a ScriptManager with EnablePageMethods = true
Then you need a method in your page's codebehind that is decorated with [WebMethod]. That method will be responsible for the call to the database
[WebMethod]
public string GetNewData()
{
// Get Data
// maybe serialize and return
}
Then your jQuery needs to looks something like this:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetNewData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, msg) {
// Do something with data
}
});
The success callback will need to process the returned data and manually populate the control's drop down list. The other option would be to get that serialized data from a Web Service (asmx). It would function much the same.
Hope that helps!
I am getting a JSON object from a webMethod by the call below and I set some textBox values based on the returned objects attributes.
Problem is, just for a moment my textBoxes are populated but then immidiately they return back to empty.
Do I make a mistake or I cannot make DOM elements modifications within a success function?
Thanks.
var ajaxCallOptions = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JQuery/Chapter16-AJAX/PersonWebServices.asmx/GetPerson",
context: document.body,
data: JSONObject,
dataType: "json",
success: function(data, textStatus, XMLHttpRequest){
var myPerson = data;
jQuery("#"+"<%=txtFirstName.ClientID %>").val(myPerson.d.FirstName);
jQuery("#"+"<%=txtLastName.ClientID %>").val(myPerson.d.LastName);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('Error: '+textStatus);
} };
jQuery.ajax(ajaxCallOptions);
The returned data is:
Additional Note:
{"d":{"__type":"BusinessObjects.Person","FirstName":"Burak","Id":"001","LastName":"Ozdogan","Department":"Information Technologies"}}
and this is a function which is bound to click event in the form:
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="loadPerson($('.personId'));"/>
If your $.ajax() is fired via a submit the default behavior is likely happening, and reloading the page.
Use return false; or event.preventDefault() at the end of your submit handler if that is the case.
$('.mySubmitButton').submit(function() {
// Send ajax request
return false;
});
or:
$('.mySubmitButton').submit(function( event ) {
event.preventDefault()
// Send ajax request
});
This same technique is used for links created from <a href=''> elements when you want to prevent the default behavior, or for any other element that has a default behavior for that matter.
I suggest use of FireBug or similar to examine the content being returned by the AJAX call. Failing this, try alerting the data which is returned.
Is the data returned the expected data?
Thanks Patrick.
It worked after this modification:
<asp:Button ID="btnSearch" runat="server" Text="Search"
OnClientClick="loadPerson($('.personId'), event); return false;"/>
I've got this textBox which triggers off an ajax request using jQuery:
<asp:TextBox ID="postcodeTextBox" runat="server" Text='<%# Bind("POSTAL_ZIP_CODE") %>'>
$(document).ready(PageLoad);
function PageLoad() {
$(container + 'parentProjectTextBox').change(GetProjectName);
}
function GetProjectName() {
var projectNumber = $(this).val();
if (projectNumber == '') return;
$(container + 'parentProjectPanel').block({ message: '<img src="../Resources/RadControls/Ajax/Skins/Default/loading7.gif" />' });
$.ajax({
type: 'POST',
url: projectMasterWebServicesUrl + 'GetProjectName',
data: "{'projectNumber':'" + projectNumber + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: GetProjectNameOnSuccess,
error: GetProjectNameOnError
});
}
This ajax request gets a list to populate this dropdown:
<asp:DropDownList ID="cityDropDownList" runat="server" OnDataBound="cityDropDownList_DataBound">
<asp:ListItem Text="...Select..." Value="0">
</asp:ListItem>
</asp:DropDownList>
Everything works fine. The only problem I'm having is that when I update my formView priod to saving that record I can't see the value that was set to that dropdown. As I'm populating this dropdown in the client side I supose ASP.NET loses track of that ....
Does anyone have any insights?
Apparently when I switch on/off the EnableEventValidation property for that page I sometimes get the correct value.....
Thanks !
You should create a hidden field store that value. Update that HiddenField in your Javascript and then read it on the server side. Also, if you have EventValidation=true and you change the items in the dropdown list you will get well known exceptions.
This may not be the problem...but are you checking for Page.IsPostBack in your Page_Load?
I've made that mistake way too many times.
If you are loading that drop down control from the Page_Load, and you are not checking
if (!Page.IsPostback)
you will reload the control. Then when you get the value from the drop down...the value is gone because you reloaded the dropdown.