404 Not Found calling Http Method from JavaScript in ASP - javascript

I've looked at a couple of threads now where they want to call a C# method from JavaScript in an ASP project. I can't figure out what I'm doing wrong. Here is my C# class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace Selfservice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public String GetCredentials()
{
return User.Identity.Name.ToString();
}
}
}
And here is the JavaScript I'm trying to call:
window.onload = function () {
LiveSearch();
getCredentials();
//FetchAllUsers();
};
function getCredentials() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetCredentials", "Home")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf­8',
data: JSON.stringify(""),
success: function (cred) {
alert(cred);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
I keep getting a 404 Not Found status back. It's an ASP site that's deployed on an IIS, on one of my workplaces servers. We are using Windows Authentication, so I'd like to get the credentials of whoever is logged in and store it for something else later.
I'm kind of at my wits end here. Anyone got any ideas?

Have you just tried to reach "/Home/GetCredentials" as URL? Also like mentioned, change to GET method, remove the contentType and change dataType to "text" as your controller is not returning JSON.

Related

how do i call web service from within a web service

i am really new to the REST world, or in fact the WebApp side of java, so please don't mind if it's a silly question.
I have a web page where pressing a button will call the following JS function:
function testFunction(){
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource",
type: 'get',
success: function (data) {
console.log(data)
}
});
});
}
where the above url is handled by my OWN web service(which is in java), that is the above GET will call the following Web Service:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}}
All i wanna do here is instead of returning "Got It", i wanna call another javascript function(dedicated to handle server kind of request) involving EXTERNAL rest call such as this:
function externalResource() {
$(document).ready(function() {
$.ajax({
url: "any_external_rest_call",
type: 'get',
dataType: 'json',
success: function (data) {
document.getElementById('demo').innerHTML = "Perfect"
}
});
});
}
where i wanna return the data from the externalResource function to getIt() to finally the testFuntion(), i know its possible, but couldn't find much of the details online. It would be really helpful if someone could clear this up to me.
You cannot call JavaScript code from your REST method in Java. However, you can use the ClientBuilder of the javax.ws.rs.client package.
Your method could look like this:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
client = ClientBuilder.newClient();
target = client.target("http://api.anotherRestService.com/details/")
return target.request(MediaType.APPLICATION_JSON)
.get();
}
}
This is just an example, I didn't try it in a real environment, but this is how you can do it. Now, you can call with your JS method testFunction the REST method of your Java backend. In you REST method getIt you call another rest service with the created client. The result of the second rest call is returned to your JS method testFunction.
Take a look at his: RestTemplate. This is Spring, however. Seeing as you are using JAX-RS maybe take a look at this: Jersey.
The flow you describe is not possible, it is however possible to chain several requests while using data from the response of the previous response:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource1",
type: 'get',
success: function (data) {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource2?id="+data.id,
type: 'get',
success: function (data) {
console.log(data)
}
});
}
});
});
If you wish to call another URL from your server, its a redirect call. Following would be an example server side code if you are using Spring framework.
#RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.google.com");
return redirectView;
}
As others have mentioned, you can also use Spring RestTemplate to do this.

How to convert data from JSONP to JSON

I'm using an API that returns a JSON. Unfortunately because of CORS, I'm unable to set datatype as JSON and have to use JSONP, which the API doesn't support.
From my understanding, I can convert JSONP to JSON by giving it a callback function. It's not working and I couldn't find solutions online. Any help would be appreciated for me to convert the JSONP datatype to JSON.
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonpFunc',
jsonp:'callback'
});
});
function jsonpFunc(data){
console.log(data);
};
Error I'm getting
Uncaught SyntaxError: Unexpected token :
The simplest way to do this is to use a server-side proxy on your server. You do not run into CORS issues with this model.
A simple example C# proxy might be:
using System;
using System.Web.UI;
using System.Net;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProcessRequest(this.Page);
}
public void ProcessRequest(Page context)
{
WebClient client = new WebClient();
string BaseUrl = ConfigurationManager.AppSettings["PassthroughTargetURL"];
string _url = BaseUrl;
context.Response.AddHeader("Content-type","application/json");
string _out = client.DownloadString(_url);
context.Response.Write(_out);
}
}
with a calling ASPX page as follows;
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Passthrough-proxy.aspx.cs" Inherits="_Default" %>
And a config entry for the remote URL, like so:
<add key="PassthroughTargetURL" value="http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL"/>
Assuming the URL you are calling is constant, you should get the expected result, but via your proxy - which is local to your server, so JSON will work as expected.
Your code would then become something like:
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://your.server/proxy.aspx',
dataType: 'json'
});
});

Get json datas from C# to javascript without using [WebMethod]

I have a C# Project, and a ASP.NET project (without database).
I want to call some methods from my C# Project, get the results in JSON and use it in my javascript without using the [WebMethod], I tried to make a Controller but I'm a little bit lost.
If you have any tips it would be nice, thank you.
The code in the controller should look like:
public class HomeController : Controller
{
[...]
public virtual ActionResult GetExample()
{
[...]
var result = ...;
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public virtual ActionResult Update(MyModel model)
{
[...]
var result = model
return Json(result);
}
[...]
}
And from your java script file you make an ajax call:
$.ajax({
url: "<path>/Home/GetExample",
type: "GET",
dataType: "json",
cache: false,
success: function (html) {
[...]
}
})
or:
$.ajax({
url: "<path>/Home/Update",
type: "POST",
dataType: "json",
data: $(#my-form).serialize(),
cache: false,
success: function (html) {
[...]
}
})
I don't have enough reputation so adding my comments here. You probably want to use Web Api here which is the reason you created controller. You probably need to refer Web Api site which will help you build controllers and expose interface to be called from javascript.
Web API

ASP.NET MVC 4 FormCollection is Empty using Angularjs $Http.post

I’m submitting a form post using Angularjs (1.2.20) to Microsoft ASP.Net MVC 4:
public ActionResult Save2(FormCollection customer)
{
//TODO: Do some stuffs...
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
However, the FormCollection is empty. I know that the data is being sent because if I change it to the following code below (using strongly type CustomerVm), it works as expected.
public ActionResult Save1(CustomerVm customer)
{
//TODO: Do some stuffs...
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
I’m using FormCollection so that I can add ASP.Net anti-forgery token in the data (instead of headers). Below is my custom javascript code. Also you can find the entire code (Visual Studio) here
You need to send the request with a content-type of application/x-www-form-urlencoded and encode the request body as such. This is a good start but it's sending the data as JSON.
var data = JSON.stringify(customer);
// FormCollection
$http({
method: 'POST',
url: '/Home/Save2',
//dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset-UTF-8',
//contentType: 'application/json; charset-UTF-8',
data: data
});
Turning the object into a URL encoded form is actually pretty complex. Thankfully, Ben Nadel has already created a transformRequestAsFormPost service to do this via a request transformer. You can give it a try by adding in his code and making this change to yours...
myApp.factory('customerSvc', function ($http, transformRequestAsFormPost) {
return {
// ...
save2: function (customer, antiForgeryToken) {
$http({
method: 'POST',
url: '/Home/Save2',
transformRequest: transformRequestAsFormPost,
data: data
});
}
};
});

ASP.NET MVC - Render PartialView with AJAX?

Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.

Categories