ajax and user control in asp .net - asp.net

I have a VB .net application in which i have an aspx page (say default.aspx). I'm loading a usercontrol (say usercontrol.ascx) in it. I need to write an ajax code in the page (in aspx page or in ascx control) which should call a method (say test()) in the user control.
$.ajax({
type: 'POST',
url: "",
data: "{'userid':" + userId + "}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
alert(data.d);
},
error: function (data) {
alert("In error ");
}
});
what I can give as url in this ajax method in order to call a method in the user control?

You can not call webmethod in usercontrol. either you have to put your webmethod inside the page or in webservice.

Pass the control name and name of your method.
For example:
url: "usercontrol.ascx/test",

Related

asp.net button disable postback but keep validation

I want to make a password recovery function where the users needs to enter the mail adress.
The mail adress has to be validated by asp.net. I dont want the site to refresh after reseting password. Thats why I disabled autopostback for my button. The problem is that disabling the autopostback also stopped the validation of the input.
I dont want to use javascript to validate the input.
So is it possible to disable autopostback but keep the validation behaviour?
Thanks alot!
This is my asp.net code:
<asp:Label>Email: </asp:Label><asp:TextBox id="emailTextbox" TextMode="Email" runat="server" CSSClass="emailTextbox"/>
<asp:Button Text="Anfordern" runat="server" CSSClass="ResetPassword" CausesValidation="True"/>
and this is the called ajax behind the button
function ResetPassword() {
alert($("#<%=emailTextbox.ClientID%>")[0].value);
$.ajax({
type: "POST",
url: "/pages/passwordRecovery.aspx/ResetPassword",
data: '{mail: "' + $("#<%=emailTextbox.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//alert(response.d);
}
});
}

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

ASP.NET: Async postback as I type in a text box

I have a TextBox control on a page that I want to use to filter a grid. I would like the TextBox control to asynchronously post back to the page as the user types in values into the text box; preferably at a certain interval (i.e. it waits 500 ms after the user stops typing before posting back.)
How can I accomplish this in ASP.net? I know that the UpdatePanel and TextBox TextChanged event doesn't give me what I need because it does not fire as the user is typing, only after the control loses focus or if the page is posted some other way.
I also don't want an autocomplete type functionality. Are there any controls that will allow me to do what I want?
You can use jQUery, fire it on keyUp() event, and set setTimeOut method before firing an ajax call.
$("#id input").keyup(function(){
var $value = $(this);
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
msgbox.css({"background-image":"none"}).html('<img src="img/ajax-loader.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
type: "POST",
url: "Default.aspx/StaticMethod",
data: "{'username': '" + $value .val() + "'}",
contentType: "application/json",
dataType: "json",
success: function(msg) {
if (msg.d != 1) {
//
}
else {
//
}
}
});
}, 200);
this.lastValue = this.value;
}//
}
});
I suppose the OnKeyUp Javascript function would best suit your needs.
Depending on what you are doing, though, this could get very costly in terms of performance...

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