Updating ASP.NET dropdown datasource from jQuery - asp.net

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!

Related

How to change label.text in asp.net?

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.

how to add a reference to the master page script manager, from the user control?

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[] { });

How to force DOM modifications done in success function persist within a jQuery.Ajax() call?

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;"/>

ASP.NET - Ajax requests with jQuery

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.

Replacing item databound with jquery ajax calls

We have a very slow ASP.NET page with a repeater. It is slow because most of the processing is done in the ItemDataBound event of the repeater. All this processing just gets 2 totals to be shown in each row.
To increase the throughput, it could be a good idea to load the repeater without ItemDataBound event and without the 2 totals.
Instead on loading the page in browser, AJAX calls can be made from each row and totals can be shown asyncronously.
Can you point to any code example where this kind of solution is achieved.
Thanks!
Indeed the jQuery.ajax() call is a good option here. You can use it to call a WebMethod defined in your codebehind
As for the server side calculation, you have a couple options:
Embed the values necessary to preform the calculation into HiddenFields within each row and pass them to your webmethod via parameters in the ajax() call.
Pass a unique ID for the row using a similar method as above (HiddenField) and do your calculation based on that ID.
As for the code, it could look something like this:
$('span.show-total').hover(
function(){
// Show panel here
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: '{"uniqueId":"' + $(this).find('input[id$=YourHiddenFieldID]').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
alert(msg.d);
}
});
},
function(){
// Hide panel here
}
);

Resources