Calling a C# method from JavaScript - javascript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.

Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Related

Sending Ajax to controller

I am trying to get live validation on a register form that tells the user if the username they are trying has already been taken or not. I am using jQuery to detect change in the input and want to send the username they type as an AJAX to a Spring controller I have set up. Eventually it will plug it into a query and return if that username has already been registered. I am having trouble with the AJAX. Any ideas on how to accurately send the request?
My AJAX:
$(document).ready(() => {
function checkPassword() {
let usernameGiven = $("#username").val();
$.post( "/check",
{username: usernameGiven} ,
function(data) {
console.log(data)
})
}
$('#username').on('input', () => {
checkPassword()
});
});
My Controller:
#PostMapping("/check")
public String checkUsername(#RequestParam(name = "username") String username){
}
I haven't used jQuery in a long time but I don't think you can pass data with your post using that syntax. Try:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is the type of data you expect back from the server (xml, json, script, text, html).
While you're testing this, make sure you're actually returning some data back from your controller too, even if it's just mock data for now.
Maybe can work if you use:
<input id="username" onBlur="checkIfUserExist()">
Make a javascript function:
function checkIfUserExist() {
$.ajax({
url: "/check",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
console.log(data); //content user availability status
},
error:function (){}
});
}
}
Think I found what I was looking for. This is working for me. Let me know if you think there is a more efficient way of doing this.
#RestController
public class TestController {
#GetMapping("/getString")
public String getString(#RequestParam(name = "username") String username) {
return JSONObject.quote(username);
}
}

ASP.NET/WebAPI: $.ajax has 404 and $.getJSON has Uncaught RangeError: Maximum call stack size exceeded

I'm working on a ASP.NET web API with a C# project that I try to call from JavaScript.
Here is my JavaScript:
function LoadGraph() {
var file = document.getElementById("file-datas");
if ('files' in file)
{
if (file.files.length == 0) {
Console.log("Empty file");
} else {
var text = file.files;
/*$.ajax({
url: "api/Graph",
type: "POST",
dataType: "json",
processData: false,
contentType: false,
data: $(text).serialize(),
cache: false,
success: function (data) {
console.log(data);
}
})*/
//$.getJSON('api/Graph', file, function (data) { console.log(data) });
}
}
And here is my Controller:
[Authorize]
[RoutePrefix("api/Graph")]
public class GraphController : ApiController
{
// POST: api/Graph
[HttpPost]
[Route("All", Name = "LoadGraph")]
public IHttpActionResult LoadGraph(string text)
{
RecursiveGraph result = test.SecondMethodFruchterman(text);
return Ok(result.name);
}
}
As you see I tried two methods in my JavaScript:
The first one with $.ajax makes POST http://localhost:53497/Home/api/Graph 404 (Not Found).
The second one with $.getJSON makes Uncaught RangeError: Maximum call stack size exceeded.
result.name is a string but I want to transfer result itself after solving these problems and getting something that works.
I don't know which one of the two method is better to use.
I don't know why I get a 404 error on $.ajax and no on $.getJSON.
And I don't know why I get this Max call stack error since it seems to appear when recursive functions are called and it's not the case here.
The first problem is that the resolved URL is POST http://localhost:53497/Home/api/Graph 404 (Not Found) which is wrong since your URL is actually supposed to be http://localhost:53497/api/Graph. To fix, prepend your AJAX urls with a /.
The second problem is likely the server error being returned as text to your web client. It is probably due to your recursion never terminating. I can't see that code in detail, but RecursiveGraph result tips me off. I'd bet on your recursive method never terminating, which would definitely max out the callstack.
I think you shall change your ajax call to this:
$.ajax({
url: '#Url.Action("LoadGraph", "Graph")',
type: "POST",
traditional: true,
data: {
text: $(text).serialize()
},
cache: false,
success: function (data) {
console.log(data);
}
})
You get the 404 (not found error code) because your ajax post url api/Graph is just your referring to your controller
Why did you even change your controller RoutePrefix to "api/Graph"? Is there a special reason for doing this?
Here the corrected code
//[Authorize]
[RoutePrefix("api/Graph")]
public class GraphController : ApiController
{
// POST: api/Graph
[Route("LoadGraph", Name = "LoadGraph")]
public IHttpActionResult LoadGraph([FromBody] string text)
{
RecursiveGraph result = test.SecondMethodFruchterman(text);
return Ok(result);
}
}
I need to add [FromBody] because string is not a model.

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Ajax calling WEB API throwing a Parser Error

So I am trying to make an AJAX call to get JSON information from a WEB API. The WEB API method seems to be working properly and when I try to access it via Fiddler, it returns a result:
When I try to access it via JQUERY AJAX, it fails and says that there is a parser error. Below is my AJAX call:
$.ajax({
url: 'http://example:port/api/values/',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
alert("works");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
Below is my WEB API Method:
[System.Web.Http.HttpGet]
public List<Users> Get()
{
List<Users> user= (from m in new DataAccessLayer.MapRepository().GetUsersRelatingTo("UserName")
select new CommonLayer.Views.Markers
{
ID= m.UserID,
}).ToList();
return users;
}
I would appreciate any sort of tip, thanks!
Edit: Below is more information on the error:

Web service Spring ajax call

I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks
Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.

Categories

Resources