How to send JSON to MVC API (using Ajax Post) - asp.net-mvc

I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());

Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -

I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.

Related

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

AJAX POST to MVC Controller showing 302 error

I want to do AJAX POST in my MVC View. I've written the following:
Script Code in View
$('#media-search').click(function () {
var data = { key: $('#search-query').val() };
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
});
Controller Code
[HttpPost]
public ActionResult Search(string key)
{
return RedirectToAction("Simple", new { key=key });
}
But on AJAX POST I am getting the 302 found Error
The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
If not, you'll need to return something more meaningful than a redirect instruction from your controller.

Ajax json post is not working

I need to pass a json data to the controller. hence i have created a ajax post. But it is not calling the action method.
function DeleteRow(postData) {
$.ajax({
url: '#Url.Action("DeleteGridRow","Project")',
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
}
My Actionmethod
[HttpPost]
public JsonResult DeleteGridRow(string postData)
{
return Json(null);
}
Please help
If you have separated your javascript file from your cshtml or vbhtml page, then this is not going to work. Your URL would be interpreted wrongly. You should pass URL where you are submitting to your function DeleteRow. Something like this:
$("#myForm").submit(function() {
var url = $(this).attr("action");
var data = Use your method to collect data or $(this).serialize();
DeleteRow(url, data);
});
function DeleteRow(url, postData) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
Something like this should work.

Ajax sucess function not called (returning data)

I have a simple $.ajax call that i did a million times before
$.ajax({
type: "POST",
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
and a controller that accepts my data without a problem but i can't seem to return data to the sucess function.
[HttpPost]
public ActionResult MyAction(MyClass data)
{
//do something
return Content("blabla");
}
What seems to be the problem?
EDIT:
Everything was ok but i wrote sucess instead of success.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
alert(data);
}
});
It could be that you need to return a json-p style response... if the javascript and server side code are running on different domains then this is almost certainly the case.
Take a looks at http://api.jquery.com/jQuery.ajax/ for some more details.
I suggest you try :
$.ajax({
type: "POST",
datatype: "text",
async: false,
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
The idea is if you ask for a synchronous call and request type of text then it should get around the jsonp / callback issue.
Hopefully worth a try :)

Return a PartialView from $.Ajax Post

I have the following code;
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "json",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
}
And in my controller;
[ValidateInput(false)]
public ActionResult jQueryAddComment(Comment comment)
{
CommentSection commentSection = new CommentSection();
//ya da - ya da
// fill the commentsection object with data
//then
return PartialView("CommentSection", commentSection);
}
However, when I get back to the page the success alert doesn't happen. Can anyone see the flaw in this logic?
Your expecting JSON in the .Ajax POST, but in the ActionMethod your returning a PartialView?
Try:
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "html",
data: json,
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
}
}
Unless it was copied over wrong it appears you are missing some closing tokens.
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "json",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
} //<-- added close for anonymous function
}); //<--added close/semicolon for ajax function
Also, you are POSTing but it your action doesn't appear to have the [Post] attribute. When you run this in the debugger does a breakpoint on your action get hit?

Resources