I'm working on an ASP.Net user control, which is using Jquery UI for rendering controls such as modal dialog, accordion, etc.
I've ajax post method in the javascript file. The javascript file lies in JS folder under Root.
function ajaxPost(someData) {
var serviceUrl = "../Test.asmx/eidTasks";
var param="{'data':'" + someData + "'}";
$.ajax({
type: "POST",
url: serviceUrl,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ajaxPostSuccess,
error: ajaxPostFailed
});
}
function ajaxPostSuccess(){
alert("Post Success");
}
function ajaxPostFailed(){
alert("Post Failed");
}
My ajaxPostFailed always gets triggered. I suspect that the issue is I'm not able to reference the .asmx service correctly. I saw while debugging that the service was not at all hit. Any pointers what could be the correct way to give the service URL path here.
I've tested the service separately and it does have the [System.Web.Script.Services.ScriptService] block uncommented to allow AJAX calls.
EDIT
How can I call a webmethod (wrapped in a asmx file) from a JS file? Provided, both are part of same ASP.Net solution with the .js file inside JS folder under ROOT directory. The asmx web service is directly beneath ROOT.
If the issue is with the .asmx file not being correctly referenced from your JScript, try resolving the path using ResolveClientUrl() method. For e.g., var serviceUrl = '<%= ResolveClientUrl("~/Test.asmx")%>'+"/eidTasks"
Related
In my ASP.NET MVC application I have a problem in calling WebAPI controller by ajax statement.
Here is my code:
$.ajax({
url: 'api/cartitems',
type: self.cartItem.id == null ? 'post' : 'put',
contentType: 'application/json',
data: ko.toJSON(data)
})
.done(self.successfulSave)
.fail(self.errorSave)
It produces an error 404 - file not found.
I've tested different possibilities and only one that works is using whole URL path.
$.ajax({
url: 'http://xx.yyy.zz.vvv/APP_NAME/api/cartitems',
type: self.cartItem.id == null ? 'post' : 'put',
contentType: 'application/json',
data: ko.toJSON(data)
})
.done(self.successfulSave)
.fail(self.errorSave)
Is it possible to not use the full path?
I wonder whether, there is an error in ASP.NET MVC configuration.
On developer environment it works with simplified URL in ajax call.
And I can't believe that Microsoft forces developers to adjust URL address on every productive system.
I bet the Url.Action construct will work. It ties into your routing configuration to produce a valid url.
In .JS Script
url:'#Url.Action("api","cartitems")',
In .xxhtml
url:'#Model.YourPostabckUrlVariable',
Does anyone know if it's possible to use jquery/ajax to call a c# (or any other .net) function in another project within the same solution?
Let's say that the solution's name is ExampleSolution , the name of the project from which I call the target function is Project.Source and the name of the target project is Project.Target,
and the name of the target function is TargetFunction().
I've tried following in an .js file in the Project.Source:
$.ajax({
url: '/ExampleSolution/Project.Target/TargetFunction',
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
Then I've modified the url-line in several ways but never succeed.
Do you have any advice?
Thank you all for your fast answers.
I found a solution for the problem and I'd like to share it just in case anybody faces the same problem in the future.
In the .js file before I call the $.ajax function I create a variable with help of window.location which points to the url to the targetfunction of the running target-project and use the variable in the ajax-function. So you don't point to another project. You point to url of running project.
Just as easy as it sounds.
Below follows the solution:
var url = window.location = 'http://localhost:13105/TargetFunction';
$.ajax({
url: url,
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
});
You can only call functions in the Code Behind because they're being registered by the web server.
If you want to have a function accessible outside the Code Behind it needs to be registered as a ASMX or WCF service.
See Creating and Consuming Your First WCF Service for setting up a WCF Service.
Once it is setup and running you can use Ajax to call the methods just like you would in the Code Behind.
$.ajax({
//Path to WCF Server and Target Method
url: "http://localhost:PORT/wcfsvc/FooService.svc/Foo",
type: 'get',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$(document.body).append(data);
}
});
See also: Consuming WCF from jQuery as JSON
The short answer is "No, it isn't possible." Front-end code (like jQuery and AJAX) run on the client's machine, but C# functions are back-end and run on the server. There's no direct connection between them.
The longer answer is "Not directly, but there are ways to do something similar." Your easiest option is to use AJAX to POST to another controller/action on your server and then process the response. This is close to what you were doing, but you were slightly off. Rather than the url being a function, the url has to be an actual url on your website. Using /Functions/CallTargetFunction as an example, you would then create a controller like this:
public class FunctionsController : Controller
{
public ActionResult CallTargetFunction()
{
return Content(TargetFunction());
}
}
Note that doing this means anyone who visits http://yoursite.com/Functions/CallTargetFunction will get the result of that function.
I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?
So I have something like this situation:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?" + url);
where url holds GET parameters. But imageProcess.aspx is different than the file I'm in (dashboard.aspx) and I need to reference some panels within my dashboard.aspx file. So my question is, using the .load() function, or even any function that could get the job done, how do I call a function, with GET parameters, in the dashboard.aspx code behind file? I'm fairly new to the .NET framework so I apologize if the question sounds elementary.
In your imageProcess.aspx.cs create a webmethod like:
[WebMethod]
public static string YourMethod(your parameters)
{
//Do Your Work
}
and in your dashboard page, in javascript use jquery to send request your webmethod like:
$.ajax({
type: "POST",
url: "imageProcess.aspx/YourMethod",
data: "{parameter1Name:'" + JSON.stringify(parameter1value) + "', Parameter2Name:'" + JSON.stringify(parmeter2Value) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do your success work, keep in mind that your returned data will be in data.d
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// do your failuer work
}
});
I hope it will give you a guidance to achieve your task.
Just to make sure: You are trying to access functionality from a different aspx page than the one you are currently on.
I'm not entirely sure if you can do that the easy way by java script. Maybe someone else knows a better way, but the way I would do it is creating ashx service page which will handle your request so you can provide the data you need (in your case an image)
For more information see http://www.dotnetperls.com/ashx
I am trying posting a data to a web service. And this service in a different project in same solution.
This project name is WebServices and web service's name is HastaTahlilUyariService.asmx.
My code is here:
$.ajax(
{
type: "POST",
url: "WebServices/HastaTahlilUyariService.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert( 'hata'+ msg);
}
}
);
I think my url is wrong. How can i give correct url.
Thanks in advance...
You might want to change your url to something that isn't relative to where you are right now, such as url: '/WebServices/... (initial slash...)
Using the firebug addon for firefox, you can inspect the AJAX callback and see what exact URL is being requested. You can copy that URL, and you should be able to point your browser to the URL of the asmx (i.e. without the last parameter, which is the method name).
Other than that, you need to make sure you've uncommented the ScriptService attribute in the top few lines of the asmx code file. It is commented out by default, but it needs to be there to allow jQuery to access the webservice.
First of all: build your webservice, and configure it to run under something like http://localhost/services/myservice.asmx in IIS Configuration Manager. Open IIS Manager, rightclick on website -> New Virtual Directory; and navigate to the folder where your webservice is located. Name the virtual directory then services.
Then call the service with it's fully qualified url like http://localhost/myservice.asmx/function.
The most easy way to do what you are trying to do (well, I guess)
Create the method you want to call in your codebehind like
[WebMethod]
public static object MethodToCallFromAjax(string argument)
{
//do something
return result;
}
Then add a ScriptManager to your aspx page; and set enablePageMethods=true. Then call your method from JavaScript like:
PageMethods.MethodToCallFromAjax("argument value", function(msg) { alert(msg); });
edit: removed some stuff about json and asmx that wasn't true :-)
Another option to look into is the standard XMLHttpRequest object that is built into the browser (for IE 6 you have to use the ActiveX object with the same name). It makes calling XML services pretty easy, although you end up having to some of the SOAP formatting yourself.
Wikipedia entry for XMLHttpRequest