From Asp.Net MVC UI(View) I am calling a Asp.Net WebApi through Ajax Call.
$.ajax({
type: "POST",
contentType: "application/json",
url: "api/UpdateEmployees",
data: undefined,
success:
function () {
EmployeesPage();
},
error: function (err) {
Error(err);
}
});
When I publish the WebSite in IIS as a Site it is working fine.But if I publish the WebSite under "Default Web Site" it is not working because it is expecting the url as "EmployeeWebSite/api/UpdateEmployees" where EmployeeWebSite is my virtual directory under "Default Web Site".
I should append url based on where the WebSite is hosted.Can anyone help me with this? I want my website to work in both cases.
I am deploying both ways using localhost.
use this code in layout.chtml or In your current View
<script type="text/javascript">
var baseurl = '#VirtualPathUtility.ToAbsolute("~/")';
</script>
After that u can use your Base URL varible
$.ajax({
type: "POST",
contentType: "application/json",
url: baseurl +'api/UpdateEmployees',
dataType: "json",
success:
function () {
EmployeesPage();
},
error: function (err) {
Error(err);
}
});
Tip : Dont put undefined in your $.ajax if you not parsing any data Remove it .
Have a grate day
Related
I am developing my first web app using angularjs , created a aspx page , added the controller. When I debug in local ASPX page is getting opened and Controller also working fine , but when I call the save function in angular . It is returning the status code as not authorized .
below is the call i have made
$http({
method: "POST",
url: "Login.aspx/SaveOrganizationName",
dataType: 'json',
data: { },
headers: { "Content-Type": "application/json" }
}).
Any suggestion, how to fix ?? I have set the project to run on IIS. as I'm not having enough idea on this , please explain me detailed
thanks
I have implemented one MVC application with Basic implementation as per this
Now when I call this action method from my Webform application using AJAX, it did not asking for credentials and throwing an 401 error.
This is my ajax function:
function testSS()
{
$.ajax({
url: 'http://localhost:52099/Controller/Sample',
type: 'GET',
success: function (result) {
$("#ctl00_cphPageContent_SSlbl12").val(result);
},
error: function (xhr) {
alert(xhr);
}
});
}
How can I call authenticated method from webform project?
Thanks!
In order to make this work, you need to add an Authorization header, containing base64-encoded login and password.
To encode base 64, you can use btoa()
var authHeader = window.btoa("login:password");
Now, you can add this header (see $.ajax documentation)
$.ajax({
url: 'http://localhost:52099/Controller/Sample',
headers: { Authorization: authHeader },
type: 'GET',
success: function (result) {
$("#ctl00_cphPageContent_SSlbl12").val(result);
},
error: function (xhr) {
alert(xhr);
}
});
Please note this will not be very secure, because login/password are known from the client, and sent in an easily readable way, so very easy to be found by an attacker.
If the webform page and MVC action are in the same project, and the user is ogged on your website, you should probably use the asp.net [Authorize] attribute instead : it will check the auth cookie, and not rely on a login/password, it's much more secure.
Recently I was faced with some strange server behavior - it started to return a 500 error at several ajax POST requests. All was working fine before. GET requests work fine. I have made Visual Studio trace my code exceptions but I still cannot see requests coming in while debugging. Do you have any ideas?
Example
$.ajax({
type: "POST",
url: "/home/some-action",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
}
});
[POST("some-action")]
public ActionResult SomeAction()
{
return new JsonNetResult("success request");
}
Update
I use this prefix for my controller:
[RoutePrefix("home")]
So you're using Attribute Routing?
I can't see your Controller but I assume you're missing the Route for /home in the controller, or removed it from [POST("/home/some-action")]
We need more information though. Current assumption is the URL doesn't exist.
Is it possible to load and save data to/from a grid using c# code in the back from an aspx page, or does one have to use a web service (or PHP)? I have tried and failed using JSON.Net to map a very simple structure to code a backend structure
Is it possible to use JQuery (an ajax GET I presume) to make a call to a method in the backend code file (.aspx.cs)? I have tried using code from various posts on this forum, but there is little information on the backend code (c#), and all seem to refer to web services. Any help/advice would be much appreciated.
Here is the JavaScript code associated:
var handsontable = $container.data('handsontable');
$(document).find('button[name=load]').click(function () {
$.ajax({
url: "Default.aspx/getJSData",
dataType: 'json',
type: 'GET',
//contentType: "application/json; charset=utf-8",
success: function (res) {
handsontable.loadData(res.data);
$console.text('Data loaded');
},
error: function () {
$console.text('Load error');
}
});
});
You still need to do an Ajax call but you don't need to do a web service (you can). The function you want exposed to the Ajax call put the [WebMethod] Attribute on and an use a Script Manager with the EnablePageMethods attribute set to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Method to Access:
[WebMethod]
public static void SomeFunction(string message, string name)
{
}
Ajax call using jQuery
(function($) {
$.ajax({
type: "POST",
url: "test.aspx/SomeFunction",
data: "{message:'Hello World', name: 'Bob'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
}
});
});
Reference: Using the WebMethod Attribute
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?