MVC Web Api not getting called from javascript ajax - asp.net-mvc

I have a Durandal/Hot Towel test app I'm trying to wire up. I have the below ajax call but I'm getting a 404 error.
GET http/.../api/Pizza/GetPizzasByOrderId?%22a8926610-a713-494c-bb15-46f6487a01c7%22 404 (Not Found)
I can manually change the url to:
http/.../api/GetPizzasByOrderId?orderId=a8926610-a713-494c-bb15-46f6487a01c7
It works. But I would like to know why the other call isn't working or more so, why is the ajax messing the parameter up in the URL and not as data like it does with complex objects. I have a get and a save that is working just fine. The get has zero params and the save is passing a complex object in.
C# Web Api Controller:
public class PizzaController : ApiController
{
[HttpGet]
public IEnumerable<Pizza> GetPizzasByOrderId(Guid orderId)
{
return DATA.GetPizzasByOrderId(orderId);
}
}
JAVASCRIPT:
var dataCall = $.ajax(config.getPizzasByOrderIdUrl, {
data: ko.toJSON(orderId),
type: "get",
contentType: "application/json"
});
Should I just change my JavaScript code to the below and be done with it or is there a better way to talk to the Api?
var getPizzasByOrderId = function (orderId) {
return Q.when($.getJSON(config.getPizzasByOrderIdUrl + "?orderId=" + orderId));
};

You could either use the code as you have it in that last code block, or you could pass in an object in place of your orderId as in the code block below. Either way, the difference is that the orderId parameter is being named.
var dataCall = $.ajax({
url: config.getPizzasByOrderIdUrl,
type: "GET",
data: {orderId : orderId},
});
In regard to why $.ajax() works fine for your POST, you can check this out pretty easily by running these two bits of code and viewing the requests that go across the wire. I recommend using google chrome.
Load a page that has jQuery loaded
Open the developer tools and go to the console
Enter the following code snippet
$.ajax("", {
data: {orderId: 123},
type: "get",
contentType: "application/json"
});
Switch to the network tab and click on the one that ends in ?orderId=123
Notice that it does have the data appended as query string parameters
In the snippet above, replace the "get" with "post"
After you hit enter, you should see another request on the network tab of the developer tools.
Notice that when changing nothing but the request type, the data is moved from the query string to the body. As noted in the comments, WebApi will pull from the body of the request and use the model binder to populate the complex object.

Related

What do I do with low Scores in reCAPTCHA v3?

I have set up reCAPTCHA v3 on my ASP.NET MVC project. Everything is working fine and is passing back data properly.
So the code below depends on another dll I have, but basically, the response is returned in the form of an object that shows everything that the JSON request passes back, as documented by https://developers.google.com/recaptcha/docs/v3
It all works.
But now that I know the response was successful, and I have a score, what do I do? What happens if the score is .3 or below? Some people recommend having v2 also set up for secondary validation (i.e. the 'choose all the stop signs in this picture' or 'type the word you see'). Is that really the only 'good' option?
Obviously the code isn't perfect yet. I'll probably handle the solution in the AJAX call rather than the controller, but still. What should I do if the score is low?
I read this article
reCaptcha v3 handle score callback
and it helped a little bit, but I'm still struggling to understand. I don't necessarily need code (although it would never hurt) but just suggestions on what to do.
VIEW:
<script src="https://www.google.com/recaptcha/api.js?render=#Session["reCAPTCHA"]"></script>
grecaptcha.ready(function () {
grecaptcha.execute('#Session["reCAPTCHA"]', { action: 'homepage' }).then(function (token) {
$.ajax({
type: "POST",
url: "Home/Method",
data: JSON.stringify({token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
CONTROLLER:
[HttpPost]
public void ReCaptchaValidator(string token)
{
ReCaptcha reCaptcha = new ReCaptcha();
Models.ReCaptcha response = new Models.ReCaptcha();
response = reCaptcha.ValidateCaptcha(token);
//response returns JSON object including sucess and score
if (response.Success)
{
//WHAT DO I DO HERE????
}
}
Ended up getting the answer from another forum. Basically, the answer is "anything you want". There is no right or wrong when handing a successful response.
So what could be done, is if the response is successful and CAPTCHA doesn't throw a flag, do nothing. But if CAPTCHA is unhappy, you could display an alert or a banner that says 'could not process', or you could even add in CAPTCA version 2, which would make them do the picture test or the 'I am not a robot' checkbox, etc.

Catch and pass hangout url to my rails app

I have a button to start a google hangout, everything works great, now I need to get the url using the
gapi.hangout.getHangoutUrl();
but I since this is a JS on my server, I know is possible to pass this to my app. But I don't know how (AJAX or anything else). I need this, because other user could join to this hangout.
Any suggestion with code would be appreciate
Within your hangout script....
Include jQuery - it's useful for X-browser support.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Get the Hangout URL:
var hoUrl = gapi.hangout.getHangoutUrl();
Get/Post the hangout URL to your server:
var uri = encodeURI(server + '?hoUrl=' + hoUrl);
$.ajax(uri,
{
async: true,
beforeSend: function(request) {
// Any beforesend code goes here, e.g. adding headers.
},
data: data,
error: function(jqhr, status, error){
// Error handling goes here.
},
type: verb,
success: callback
});
Handle the AJAX GET request and do your magic with the hoUrl parameter.
To clarify further:
A URL is formed before the AJAX get request to include a GET parameter, hoUrl, that has the hangout URL in it. Your server just needs to use whatever CGI/parameter parser to retrieve the 'hoUrl' parameter and then do whatever backend magic you want to do with it. Hope that helps to clarify.

c# MVC best way to make use of AJAX

In terms of making a an AJAX call, we have use the following method:
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("CheckPhone", "Progg")',
data: { input: WebPhoneNum
},
success: function (iReturn) {
if (iReturn == 0) {
alert(Phone Number must be in format (XXX) XXX-XXXX. Please Re-Enter');
submitval = false;
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")"); // Boil the ASP.NET AJAX error down to JSON.
alert('Call to CheckPhone failed with error: ' + err.Message); // display the error raised by the server
}
});
Notice how it makes a call to the controller and returns a value. I was wondering if there was a better way of doing this. I know .NET MVC has some ajax calls built in but couldn't find one that fits what I am doing below. I know .NET MVC has a ajax call build that with a hyperlink but that is not what I need. I just need to make a call to the controller that returns some value(s).
THanks
There's only one thing that you need to fix:
async: false
must become:
async: true
because otherwise you are not doing AJAX. You are sending a synchronous request to the server freezing the client browser.
Other than that you seem to be doing some remote validation with this AJAX request. You probably might take a look at the [Remote] attribute that's built in and which avoids you writing all this code. All you need to do is decorate the view model property that needs to be validated with this attribute and then enable unobtrusive client side validation by including the proper scripts.
try to validate the format of a input with ajax?
I recommend you learn about data annotations to validate that kind of details (please revalidate on server at submit form like a good practice)
here is a usefull tutorial http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs

Difference Between $.getJSON() and $.ajax() in jQuery

I am calling an ASP.NET MVC action
public JsonResult GetPatient(string patientID)
{
...
from JavaScript using jQuery. The following call works
$.getJSON(
'/Services/GetPatient',
{ patientID: "1" },
function(jsonData) {
alert(jsonData);
});
whereas this one does not.
$.ajax({
type: 'POST',
url: '/Services/GetPatient',
data: { patientID: "1" },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading PatientID=' + id);
}
});
Both reach the action method, but the patientID value is null w/ the $.ajax call. I'd like to use the $.ajax call for some of the advanced callbacks.
Any thoughts appreciated.
Content-type
You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.
More about that content-type here: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
Data
The data is correct as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.
You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.
JSON
It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.
Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.
So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:
$.ajax({
type: 'POST',
url: '/Services/GetPatient',
data: { 'patientID' : 1 },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading PatientID=' + id);
}
});
.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc
N.B .load, .get and .post are also simple wrappers around the .ajax method.
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.
$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.
Read More .. jquery-post-vs-get-vs-ajax
The only difference I see is that getJSON performs a GET request instead of a POST.
contentType: 'application/json; charset=utf-8'
Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.
with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

JSON parameters auto. convert to lowercase when ajax request made to MVC action method?

Would anybody know why my parameter is being "converted" to lowercase when it hits my ASP.NET MVC controller action?
I can only assume it is being converted as looking at data value just prior to the ajax request it is in correct casing, but then when debugging my action method within .NET during the ajax request and checking the incoming parameter, it has been converted to lowercase?
This is causing dramas for me as I need to keep the case entered by the user.
Code below, example data being sent is: 'SimpleDATATest1'
$.ajax({
type: "GET",
url: "/configuration/module-message-types/GetTranslation",
data: "messageToTranslate=" + messageToTranslate,
dataType: "json",
success: function(result) {
// Insert the returned HTML into the <div>.
$('#TranslationResponse').html(result.message).fadeIn('fast');
$("#" + ajaxLoadImgId).hide();
},
error: function(req, status, error) {
$('#TranslationResponse').text('Could not load example translation message, please try reloading the page.');
$("#" + ajaxLoadImgId).hide();
}
});
And MVC Action method signature is:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTranslation(string messageToTranslate)
However, when checking the value of 'messageToTranslate' it is returning as: 'simpledatatest1'.
How can I stop whatever forces at work from changing this?
Nevermind... I found this that I implemented was the culprit:
http://www.coderjournal.com/2008/03/force-mvc-route-url-lowercase/

Resources