Can we call User control code behind method using Jquery ajax? - c#

I'm trying to do something, Can we call User control code behind method using Jquery ajax ?
likes:
ASCX CODE:
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Uploads.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
ASCX.CS
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
But its will create an error please can any one what do i am wrong.

The user control doesn't have all the functionality of a page and can't be called directly.Check out the following link for complete solution
Creating a Page method (ScriptMethod) within an ASCX user control using AJAX, JSON, base classes and reflection

Related

Call a web method from code behind in ascx page

i have a script function that can call a web methods with two parameters.I want to call this script function from code behind.Here is my script function that i want to call from code behind.(I am using the .ascx usercontrol).
function BindApporment(obj, divid) {
debugger;
var username = "<%= Session["UserId"]%>";
var id = document.getElementById('<%=Hiddendocid.ClientID%>').value;
if (id != "") {
username = id;
}
$.ajax({
type: "POST",
url: "Dashboard.aspx/BindAppointment",
contentType: "application/json;charset=utf-8",
data: "{'date':'" + obj + "',userid:'" + username + "'}",
dataType: "json",
success: function (data) {
$(divid).html(data.d);
},
error: function (result) {
alert("Error ");
}
});
}
here is my web method
[WebMethod]
public static string BindAppointment(DateTime date, string userid)
{
}
...I want to call the script function BindApporment() from code behind..i have already tried a lot of code but this is not working..
I have tried these code but not working:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "BindApporment", "<script>BindApporment(" + date.AddDays(k).Date + "," + ddldoc.SelectedValue + ");</script>");
any suggestions??
You are trying to do that is not applicable to to in ASP.NET structure. A ascx control cannot process request. The ASCX can work with the data send via postbacl
You need to create ASMX service and query it with ajax request you have. How to let an ASMX file output JSON

How can I load this ASP.NET div after the page has been loaded?

There is a div on my page currently that makes a lot of requests to the server, so the pages takes about 10 seconds to load. We don't always need this data, so I want to be able to have the page load with all of the info except for this one div. Once the page is loaded 100% I want it to load this div (maybe show a loading...).
I've made an ajax request from my TrackingData.aspx as a test, but I can't seem to get this to work.
My JavaScript
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "TrackingData.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert("bye");
}
});
}
function OnSuccess() {
alert("hi");
}
And the HTML
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
The C# code is simply
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
There is a TrackingData.aspx in the same folder, and it has a method GetCurrentTime. This is just a test method, but I should be able to do the rest on my own once I get this working.
You need to add this before your static method (GetCurrentTime):
[System.Web.Services.WebMethod]
And to avoid some faults you can use json stringify for your data:
data: { name: JSON.stringify($("#<%=txtUserName.ClientID%>")[0].value)}

Can jQuery Ajax get updated by the progress of the called webmethod while running?

I have an ajax query calling a Webmethod on the server, the Webmethod does a bunch of stuff and then returns with a value (that I use in the onSuccess part of the ajax)
my question here.. is there a way to notify the client script of the status of the Webmethod while running. i.e. if its running a 100 time loop it would notify at the start of each iteration.
jQuery AJAX:
`$.ajax({
type: "POST",
url: "Whatsapp.aspx/GetProgress",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// do stuff with result
},
error: function (xhr, textStatus, errorThrown) {
alert("function error:" + xhr.statusText + "\n" + textStatus + "\n" + errorThrown);
if (window.console) console.log(xhr);
}
});`
and the WebMethod on the codebehind:
[WebMethod]
public static int GetProgress()
{
for()
{
//notify the client a start of a new iteration?????
//do lots of stuff here
}
//return the end result
}

Ajax call not working when keeping a webpage in folder in url rewriting

My ajax call
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '../User/UserRegister.aspx/InsertMethod',
data: "{'FirstName':'" + "Test" + "'}",
async: false,
success: function (obj) {
if (obj.d == 'abc') {
}
else {
}
}
});
My Method in UserRegister.aspx.cs:-**
[WebMethod]
public static string InsertMethod(string FirstName)
{
return FirstName;
}
In my Webconfig:-
<rewrite url="~/User/UserRegister" to="~/User/UserRegister.aspx"/>
My href from where i call my page:-
sbMenu.Append("<li>" + "User" + "</li>");
Note:-When I use the page outside the folder this works perfectly
Project-->UserRegister.aspx but not working when using project-->User(Folder)-->Userregister.aspx(Page).My Project is in Vs2012.I have used intelligencia.Urlrewrite dll.
Thanks in advance

AJAX not posting to WebMethod

The Form:
<form action="upload-document.aspx" onsubmit="sendAndClose();" method="post" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file" />
<input type="submit" name="submit" value="Send" />
</form>
The AJAX:
function sendAndClose() {
currentUrl = location.protocol + '//' + location.host + location.pathname;
var data = new FormData();
var file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
}
The Code-Behind:
[WebMethod]
public static bool Persist(object data)
{
return true;
}
when the form is submitted, it runs the ajax and goes straight to the error callback before entering the webmethod. can anybody tell me why?
also, after the 'var file' I had an alert to show the files name, size, etc... so it gets the file, the problem is that ajax is refusing to comunicate with the code-behind.
I had a similar problem that was solved by adding this parameter in the ajax function :
traditional: true
So try this code for your AJAX call :
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
traditional: true,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
You cannot invoke a webmethod like http://localhost:40899/upload-document.aspx/Persist. The currentUrl is incorrect.
Following on from my question in the comments section I would add that your public static bool Persist... method MUST be in the page (ASPX) and not a user-control (ASCX).
This is because the page (ASPX) is "visible" to the outside world via a URL whereas a user-control (ASCX) is only used on the server to build up the page not a URI in its own right, and therefore not accessible to external callers.
If you need to call the method in the user-control you will need to move your Persist method (with WebMethod attribute) to your page (ASPX) and then make a call from that method into your user-control (ASCX).

Categories