.NET MVC 4 API Controller not getting AJAX data? - ajax

I have a simple ajax call that is not sending data correctly. What am I doing wrong? Here is the AJAX:
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: { id : 10}
});
and here is my controller:
public class ChatController : BaseApiController
{
//
// GET: /Chat/
[HttpPost]
public int New(int id = -1)
{
return id;
}
}
BaseApiController is my own controller that has DB context in it and it inherits from ApiController. I cannot get data to send across the wire at all. New() just returns -1 every time.

try removing the data type from your ajax call. Something like this
$.ajax({
url: '#Url.Action("New", "Chat")',
type: 'post',
cache: false,
async: true,
data: { id: 10 },
success: function(result){
// do something if you want like alert('successful!');
}
});

try this
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ id : 10})
});

Please take a look at the answer of the following post
http://forums.asp.net/t/1939759.aspx?Simple+post+to+Web+Api
Basically, Web API Post accept only one parameter, it can be a primitive type or a complex object.
Change your ajax request to the following
$.ajax({
url: '/api/Chat/New',
type: 'POST',
data: { '' : 10}
});
Then change your controller as follows
[HttpPost]
public int New([FromBody]int id = -1)
{
return id;
}
If it's a complex object like a ViewModel, you don't need to use FromBody
You can read more about why this is required by reading "Using[FromBody]" section in the following article.
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Related

Ajax sending variable value to MVC controller

I am trying to send a value from jQuery using ajax call and fetch the value in the controller. Below is what I am trying, but the value of A is always null. Can someone help me where I am going wrong.
$.ajax({
type: "POST", //The type of Method being used (GET, SET, POST, etc.)
url: '/Controller1/Index',
contentType: 'application/json; charset=utf-8',
data: { A: "true" }, //Your data to pass to your Controller action
dataType: "json",
success: function (result) {
alert(response.responseText);
alert("Done!");
}
});
C# code
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost(FilterRule queryBuilder, BootstrapTableQueryType bootstrapTable, string A)
{
string B = A;
}

ASP.NET MVC Ajax: refuse to send long string

I am trying to send long string through Ajax. When the "note" string is short, it goes through fine. When it is more than a thousand characters or so, it silently fails, the action method is not called.
Ajax call:
$.ajax({
url: '#Url.Action("SaveSchoolNote")',
type: 'POST',
dataType: 'json',
data: { schoolId: schoolId, note: note },
cache: false,
success: function (data) {
}
});
Action:
public ActionResult SaveSchoolNote(int schoolId, string note)
{
...
}
Please help!

Trying to send multiple parameters to ASP.NET webAPI post method results server error 500

Iam trying to send multiple parameters with complex datatype to POST method in WebAPI but it fails with 500 server error. I will be greatful if somebody help me finding what is missing ?
Ajax:
var x={}
var y={}
$.ajax({
cache: false,
type: "POST",
data: JSON.stringify({xDto:x,yDto:y}),
url: "/api/Info/PostInfo",
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function(data) {
}
error: function(data) {
alert(JSON.stringify(data));
}
})
Action:
public IHttpActionResult PostInfo(InfoDto xDto,InfoDto yDto)
{
//post xDto and yDto to db
}
I would change the API Parameter to an InfoDto array and retrieve it from the body:
public IHttpActionResult PostInfo([FromBody]InfoDto[] xDtos)
{
}
You also have to change your JavaScript to something like this:
data: JSON.stringify([x, y])

Alias web api request model

I am trying to use ajax call on asp.net web api where i want to alias the request model property name.
However, when i post the value back to the server and receive it as request, it does not work as expected. what i intend to achieve is as follow:
When i pass the data valueA back to web api, it will mapped to MemberName. Not sure where i did wrong.
THis is what something i expect.
$.ajax({
url: '..',
dataType: 'json',
type: 'POST',
data: { 'valueA': 'ABC' },
success: {}
})
public class MemberProfile {
[JSONProperty('valueA')]
public string MemberID { get; set; }
}
[HttpPost]
public HttpResponseMessage GetMemberProfile(MemberProfile request)
{
}
You should change you JavaScript code to :
$.ajax({
url: '..',
contentType:'application/json', //here
dataType: 'json',
type: 'POST',
data: JSON.stringify({ valueA: "ABC" }), //here
success: {}
})

Jquery ajax returning null values back to controller - MVC3

I'm using jQuery ajax to build a viewmodel list and then trying to send that viewmodel to another ActionResult in order to create PartialViews. The first part works well, and I'm able to create the viewmodel (List), but when I try to send the viewmodel back to the controller to build up the partial views, everything within the viewmodel is 0. It returns the correct number of items in the list, but it seems to lose the values.
Can anyone see if I'm missing anything here?
jQuery:
$.ajax({
async: false,
type: 'GET',
dataType: "json",
url: '#Url.Action("GetMapDetails")',
success: function (data) {
$.ajax({
async: false,
type: 'POST',
dataType: "json",
url: '#Url.Action("GetMapItems")',
data: {
list: data
},
success: function (list) {
//callback
});
}
});
}
});
and the controller:
public ActionResult GetMapDetails()
{
List<ViewModel> vm = new List<ViewModel>();
//create viewmodel here
return Json(vm.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetMapItems(List<ViewModel> list)
{
return PartialView("_MapItemsPartial", list);
}
I've tried also using contentType: 'application/json' and JSON.stringify(data) but that gave me an Invalid JSON primitive error.
Any help appreciated - thanks
You could send them as JSON request:
$.ajax({
async: false,
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("GetMapItems")',
data: JSON.stringify({
list: data
}),
success: function (result) {
//callback
}
});
Also notice that I have removed the dataType: 'json' parameter because your GetMapItems POST controller action doesn't return any JSON. It returns a PartialView. So I guess you did something wrong and this is not what it was meant to be returned from this controller action because from what I can see in your success callback you are expecting to manipulate JSON.
Oh, and please remove this async:false => it defeats the whole purpose of AJAX as you are no longer doing any AJAX, you are now doing SJAX.

Resources