Ajax : Can't bind multiple parameters - ajax

Hey I am trying to bind multiple parameters in ajax post request but I am getting the following error.
Can't bind multiple parameters to the request's content.
Here is my code
MVC Api Controller Side
public void Post(Email email, PInformation pInformation)
{
//do something.
}
Ajax Call
var mail = { mail: 'myemail', Password: 'pass' };
var ppInformation = { FirstName: 'James', LastName: 'Jones' };
var datum = { email: mail, pInformation: ppInformation };
$.ajax({
url: 'url',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(datum),
success: function (result) {
}
});

You need to use a composite, so:
$.ajax({
...
data: {form: datum},
});
Your controller method:
public String controlerMethod(#RequestBody FormData form){
...
}
Your form model:
class FormData {
Email email;
PInformation pInformation;
// getters & setters
}
This solution should work, but I can't say that there is some sort of multiple RequestBody available for POST method.

Related

Parameters not populating with Ajax Call

This is my controller
[HttpPost]
public bool Sync(int? id, string name)
{
throw new NotImplementedException();
}
Here is my ajax request call that I am trying to make to this controller:
<script type="text/javascript">
var buttonClicked = document.getElementById("syncLegacy");
buttonClicked.addEventListener('click', function () { syncLegacyMake(); }, false);
function syncLegacyMake() {
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: JSON.stringify({
id: $("#Id").val(),
name: $("#Name").val()
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function () {
alert("error");
}
});
}
The controller gets hit however there are no values to the parameters. The values are both null.
When I look at the call itself on chrome console, the values are populated as these under Request Payload in the headers:
{id: "01", name: "Titan"}
id
:
"01"
name
:
"Titan"
Could anyone point out what I am doing wrong here? I have been able to do the same in .net 4.6.1 framework so not sure if framework changed has caused this?
have you tried the following things:
Using a Dto instead of separate simple types:
public class SyncDto
{
public int? Id {get;set;}
public string Name {get;set;}
}
// Controller action:
[HttpPost]
public bool Sync(SyncDto input)
{
throw new NotImplementedException();
}
Make Jquery stringify itself
Let jquery figure your ajax call out itself:
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: {
id: $("#Id").val(),
name: $("#Name").val()
}
});

ASP.NET & Ajax - How to pass value from ajax to action?

I have a few checkboxes on my page. I have some jquery in place to ensure that only one checkbox is checked at a time. I have assigned a specific value to each checkbox. The below ajax finds the checkbox that is checked and I'm grabbing the value associated to it. How do I pass that value to my action?
AJAX
$("input:checkbox").click(function () {
var PaymentID = document.querySelector('#chkBox:checked').value;
alert(PaymentID); // for test
$.ajax({
type: "POST",
dataType: "json",
data: PaymentID,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("MyAction", "Home")",
success: function () {
return PaymentID; // Failed attempt at passing data.
}
})
})
Action:
[HttpPost]
public ActionResult MyAction(string PaymentID)
{
// Magic
}
Please keep in mind i am fairly new to ajax. Thx guys.
You can pass a javascript object with name PaymentID ( same name as your action method parameter)
data: { PaymentID: PaymentID },
You do not need to specify contentType as you are sending a simply object. Also you do not necessarily need to specify dataType for your ajax call to send the data.
This should work.
var PaymentID = "some value";
$.ajax({
type: "POST",
data: { PaymentID: PaymentID },
url: "#Url.Action("MyAction", "Home")",
success: function (response) {
console.log('response', response);
}
});
Or you can use the $.post method.
$.post("#Url.Action("MyAction", "Home")",{ PaymentID: PaymentID }, function(response) {
console.log('response', response);
});

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: {}
})

.NET MVC 4 API Controller not getting AJAX data?

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

MVC3 jquery ajax parameter data is null at controller

I have a controller action that I want to update via a jquery call. The action runs, but there is no data in the parameters.
I am using a kedoui grid with a custom command in a column that I want to run some server code.
kendoui grid in view
...
columns.Command(command =>
{
command.Custom("ToggleRole").Click("toggleRole");
});
...
The model is of type List<_AdministrationUsers>.
public class _AdministrationUsers
{
[Key]
[ScaffoldColumn(false)]
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
Here is my toggleRole Script:
<script type="text/javascript">
function toggleRole(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
alert(JSON.stringify(dataItem));
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
}
</script>
Here is my controller action:
[HttpPost]
public ActionResult ToggleRole(string UserID, string UserName, string Role)
{
...
}
The controller action fires, but there is no data in any of the parameters.
I put the alert in the javascript to verify that there is indeed data in the "dataItem" variable. Here is what the alert text looks like:
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Did you try specifying the dataType and contentType in you ajax post ?
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
It looks like you are posting the whole object as one Json string, while the controller expects three strings. If you are using MVC3 the parameter names also have to match the controllers signature. Try to parse up your data object so that it matches the input expected from the controller. Something like this:
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: { UserID: dataItem.UserID, UserName: dataItem.UserID, Role: dataItem.Role },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
Hope that helps!
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Seems incorrect to me. Wouldn't you want this?
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role" : "Admin"}
Notice the "Role" : "Admin"

Resources