In my asp.net webapp I'm using a local webservice to retrieve data's. The system is in a popup (wich is an another page in fact)
So here's the jquery code:
$(document).ready(function () {
$('#ddlToBind').change(function () {
var parameter = "{'aId':'" + $("#ddl").val() + "'}";
$.ajax({
url: "../WebServicesASMX/PMywebserv.asmx/Test",
data: parameter,
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$('#ddlToBind>option').remove();
for (var i = 0; i < data.d.length; i++) {
$("#ddlToBind").append("<option value='" + data.d[i].Id + "'>" + data.d[i].Name + "</option>");
};
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
It is working good while you are in the root of site and once you launch the script in other pages the path is not correct so asmx is not reached..
I've tried with the tilde "~" in place of ../ but it doesn't work.. url: "~/WebServicesASMX/PMywebserv.asmx/Test"
Is it a possibility to specify relatives path in my jquery script?
VirtualPathUtility to the rescue!
url: "<%= VirtualPathUtility.ToAbsolute("~/WebServicesASMX/PMywebserv.asmx/Test") %>",
See this post by Rick Strahl: http://www.west-wind.com/weblog/posts/2009/Dec/21/Making-Sense-of-ASPNET-Paths
Note that for this to work the script needs to be in a page that is processed by ASP.NET e.g. aspx, ascx, MVC View. If your script is in a plain js file, you'll need to move it, or reference a javascript global variable that you define elsewhere in ASP.NET code.
use
<%= ResolveUrl("~/WebServicesASMX/PMywebserv.asmx/Test") %>
Related
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
I am new to JS, even less experienced at AJAX. I'm just trying to pass a value to the code behind and return an expanded response.
The problem is that despite the call succeeding, the string value passed from AJAX to C# is never anything other than "undefined", and it is driving me insane.
The JS
function test() {
var message = "this is a test" ;
Display(message);}
function Display(words) {
var hummus = { 'pass': words};
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: hummus,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words + "\n\nError: " + lion);
}
});}
The Code Behind
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
The end result is invariably "Your fortune: undefined. We repeat this is only a test."
I would only like to know what I am missing.
Yes this is probably a stupid question but my searches reveal nothing helpful.
Your issue is that you are trying to accept a string in your method public static string ShowMe(string pass) but you are passing a JavaScript object as your data. See when you make an Ajax call ASP.Net will do its best to match up the data you posted to the type you have in your parameter - called Model Binding. When this cannot be achieved then you get an null passed in.
So in your JavaScript you are passing a JavaScript object using this:
var hummus = { 'pass': words};
$.ajax({
....,
....,
data: hummus,
If you wish to post an object then your controller/method needs to have a C# model (class) that your JS will be bound to.
So change your method to accept a model:
// somewhere in your code put this little model
// this is what your JavaScript object will get bound to when you post
public MyModel{
// this is to match the property name on your JavaScript object, its case sensitive i.e { 'pass': words};
public string pass {get;set;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(MyModel model)
{
// you can now access the properties on your MyModel like this
string beans = model.pass + ". We repeat this is only a test.";
return beans;
}
I found two issues in your code -
Missing data: JSON.stringify(hummus),
Remove lion which variable doesn't exist.
Fix
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
Working code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Account.aspx.cs" Inherits="WebApplication1.Account" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="test()">Display Word</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
</script>
</form>
</body>
</html>
public partial class Account : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
}
Thank you both for your help. I'm going to try the Model method, the JSON.stringify was something I had tried before and ultimately worked.
Apparently the problem I was not understanding how my browser worked. No matter what changes I made I was getting the same error. The reason?
My code wasn't in tags on the page, it was in a separate js file which Chrome was caching for me, effectively negating every change I made to try and correct the problem and driving me insane in the process.
In all I've learned a new technique, Model Binding, and that location of code can dramatically effect your Javascript experience.
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
In Visual Studio, I have some Javascript code on a site I'm developing. While I'm debugging I'm using the $ajax call to "localhost". When deployed, it will need to be the actual server:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: 'http://localhost:8809/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
When I publish, I need to transform that localhost to the actual domain:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: 'http://www.mydomain.com/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
Is there an easy/automatic way to do this, similar to the way Web Config transforms work?
Many thanks!
You don't, you just omit the host, the browser will fill this in for you, like this:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: '/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
If you're actually talking about x-domain requests, which I doubt you are, then just set a global js site variable.
I recommend you to use this:
url: '<%= ResolveClientUrl("~/Account/UserNameExists/")',
If you do it this way you'll avoid problems if you:
install the app in a virtual directory instead of the domain root
move your page to a different directory level in your app
use your service from a master page or user control, which can be instantiated in different pages, an thus directory levels
You can also expose a public property in your page/user control/master page, and use it from code in the same way, i.e:
code in the page/uc/master: public string ServiceUrl { get { return ResolveClientUrl("~/Account/UserNameExists/");}
code in .aspx: url: '<%= ServiceUrl',
Are you making a call to a web service or what is the destination of this url?
When I am working with ajax calls in my web applications I usually set up the methods inside of a web service and call them like this:
$.ajax({
type: "POST",
url: "../Services/BookingService.asmx/GetVerifiedReservations",
data: paramsJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
invalidDays = $.parseJSON(response.d);
},
error: function (xhr, textStatus, thrownError) {
alert(textStatus);
alert(thrownError);
}
});
As you can see the path is relative to the rest of the files in your domain.
I have some javascript that requires a specific URL to call an ASP.NET web service.
When I run the application locally, the url is something like: http://localhost:123456/ProjectName/Default.aspx
But when I upload the application, the domain will change to:
http://myDomain.com/Default.aspx
What's the best way to capture the current URL path and pass it in as a variable to my javascript? Here is my javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:123456/ProjectName/Default.asmx/SkillsList", //CHANGE THE URL!!
//url: "http://myDomain.com/Default.asmx", //The other URL...
data: "{'like':'" + request.term + "'}",
datatype: "json",
async: true,
success: function(data) {
response(data.d);
},
error: function(result) {
alert("error");
}
});
},
minLength: 2
});
});
</script>
I'm using ASP.NET if that helps at all.
Thanks!
post to relative path
url: "/ProjectName/Default.asmx/SkillsList"
Looks like you're writing out to the aspx page. Given that, you should be able to just have ASP.Net tell you via something like
url: "<%= Request.ApplicationPath%>/Default.asmx/SkillsList"