Jquery ajax post to MVC2 action - javascript

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?

A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});

The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

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);
}
}

AJAX request cannot pass DateTime to server if using GET method

I have a form which uses Kendo controls, and when user click the button, an AJAX request gathering these controls' value will be sent to server and download a file based on these criteria. One of the controls is DateTimePicker.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '#Url.Action("MyGenerateReportMethod")',
async: true,
data: getViewModel(),
...
});
function getViewModel() {
...
viewModel.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return JSON.stringify({ para: viewModel });
}
public ActionResult MyGenerateReportMethod(MyModel para)
{
try{
...
}
}
public class MyModel
{
public DateTime? DateFrom { get; set; }
}
The above simplified code demonstrate my situation.
I have a POST ajax request to server, which passes a serialized JSON object including a Kendo DateTimePicker Value.
The server side action try to catch this JSON object as parameter and do the stuff which is irrelevant to this question.
My question is, for some reason I have to changed the request from POST to GET.
While it works using POST method, it does not work if I change "POST" to "GET".
I checked the request sent in Chrome's Developer Tools, It does sent the JSON object in the following format: (In Query String Parameters section in the Network Tab)
{"para": {
...
"DateFrom":"2016-04-13T16:00:00.000Z"
...
}
}
However, at server side, MyModel para does not seems to catch this object successfully (if I change from "POST" to "GET"). Other fields still can be bound while all DateTime fields become null.
Why is this happening, and how can I change the request from "POST" to "GET"?
Thanks.
EDITED
Based on some comments / answers, I have tried to modified the AJAX request to the following code, but it is still not working... (Same behavior)
$.ajax({
type: 'GET',
url: '#Url.Action("SumbitOutstandingReportList")',
data: getPlanViewModel(),
async: true,
...
}
function getPlanViewModel(){
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return { para: obj };
}
A GET does not have a body, so remove the contentType: "application/json; charset=utf-8", option (does no harm but its only applicable to a POST) and adjust the data so that the ajax call is
$.ajax({
type: 'Get',
url: '#Url.Action("MyGenerateReportMethod")',
data: getViewModel(),
...
});
function getViewModel() {
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return obj; // return the object, not a stringified object containing another object
}
Note this assumes the value is in a format that matches your server culture, or in ISO format (e.g. the request will be DateFrom: '2016-04-13T16:00:00.000Z')
This is happening because of, GET method is pass data in a header or url, while json data can not passed through header, change the method of passing data, which is currently in a json format.
You could do like even :
var fd = new FormData();
fd.append('data', yourData);
and send fd as a directly data object, it will work.
GET request has no body, it passes the parameters in either cookies or URL query string, so pass the data you want in a query string parameter like below:
var url = #Url.Action("MyGenerateReportMethod",new {DateFrom="_X_"});
url = url.replace("_X_",$("#DateRangeFrom").data("kendoDatePicker").value());
$.ajax({
type: 'GET',
url: url,
async: true
});

Why is my json object empty in my ASP API?

I'm trying to test my asp api.
One of the endpoints needs to take a json object from a browser. To test this I'm placing a json object into a text field and then making an ajax call to my api. When the api is hit, the json object is always null.
I've checked this post: how to pass json post data to web api method as object and that did not resolve my issue.
Here is my object:
{ "userName": "063bcdf2-36fd-4b8c-a5af-808da63744f6",
"password" : "Password"
}
Here is my ajax call:
var submission = function () {
var url = urlBase + "/api/Submission/";
var testdata = $("input[name=submission]").val();
alert(testdata);
$.ajax(url, {
type: "POST",
data: JSON.parse(testdata),
contentType: 'application/x-www-form-urlencoded'
}).always(showResponse)
return false;
};
And here is my api:
[HttpPost]
[ResponseType(typeof(SubmissionOutputModel))]
public IHttpActionResult POST([FromBody]SubmissionInputModel submission )
{
if (ModelState.IsValid)
{
SubmissionService service = new SubmissionService();
return Json(service.Submit(submission));
}
else
{
return BadRequest("Invalid Model State");
}
}
SubmissionInputModel:
public class SubmissionInputModel
{
[Required]
public string userName { get; set; }
[Required]
public string password { get; set; }
}
The alert in the ajax shows me that the data is being sent and in debug mode, the api is getting hit however the submission object is not getting set to the data being sent from the ajax call.
If anyone can help, it would be greatly appreciated!
I think you need to JSON.stringify instead of parse, since parse if used the other way around.
JSON.parse takes a string and converts it to a JSON object.
Try to stringify your testdata
$.ajax(url, {
type: "POST",
data: JSON.Stringify(testdata),
contentType: 'application/x-www-form-urlencoded'
}).always(showResponse)
return false;
};
If that doesn't work, leave out the contentType from the ajax call, or write contentType:"application/json" instead.
And also post your SubmissionInputModel. Could be some naming that is wrong there :)
What does the "testdata" look like? Is it already a string in json format?
1.The JSON.Parse parses a string as JSON only, for example:
JSON.parse('{}'); // {}
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
2.The content-type should application/json in your case, and the value you specified now is default value:
contentType: 'application/json'
3.At the mean time, as your action already marked as [POST] so the ModelBinder will try to bind your model from the request body, so it is not necessary to specify as [FromBody].
Okay, I found my happy place!
The following ajax call finally got the data through to the API:
var submission = function () {
var url = urlBase + "/api/Submission/";
var testdata = $("input[name=submission]").val();
alert(testdata);
$.ajax(url, {
type: "POST",
data: testdata,
contentType: 'application/json'
}).always(showResponse)
return false;
};
Notice that there is no JSON method on the data in the call and the contentType is 'application/json'.
Thank you everyone for your help. I hope this helps the next poor soul that runs into this problem!

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Call ASP.NET C# Controller Method from Javascript

I have a var toto in a javascript file. And I want to call a C# Controller Method who return a string and of course assign the resulted string to toto.
I tried some ways to achieve this but nothing seems to work.
Somebody can explain me the simpliest way to achieve that ? It's a Windows Azure project.
Many Thanks !
You could use AJAX. For example with jQuery you could use the $.getJSON method to send an AJAX request top a controller action that returns a JSON encoded result and inside the success callback use the results:
$.getJSON('/home/someaction', function(result) {
var toto = result.SomeValue;
alert(toto);
});
and the controller action:
public ActionResult SomeAction()
{
return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}
You have to use JSON:
Controler
public class PersonController : Controller
{
[HttpPost]
public JsonResult Create(Person person)
{
return Json(person); //dummy example, just serialize back the received Person object
}
}
Javascript
$.ajax({
type: "POST",
url: "/person/create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
console.log(result); //log to the console to see whether it worked
},
error: function (error){
alert("There was an error posting the data to the server: " + error.responseText);
}
});
Read more: http://blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

Categories

Resources