Ajax sending variable value to MVC controller - ajax

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

Related

ASP.NET MVC controller won't receive my ajax get method data

Here's a function that calls an ajax get method:
function getSubProjName(projectId) {
console.log(projectId)
var projectName = "";
//ajax get request to get the subproject name
$.ajax({
type: 'GET',
url: '#Url.Action("GetSubProjName", "Home")',
data: { projectId: projectId },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
projectName = response;
},
error: function (response) {
console.log(response);
}
});
return projectName;
}
I've checked it a billion times, projectId most definitely receives a value. If it helps, its always a numerical value.
Then I have a method in my controller that SHOULD receive the projectId and do something with it:
[HttpGet]
public JsonResult GetSubProjName([FromBody] string projectId)
{
// some code here
return Json(""); //return the code results back to the view
}
My problem is that I just can't get the controller to actually receive the data from the ajax call. All I get in my string ProjectId, in my controller method, is always null.

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

.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

how can i get list of models from ajax to controller?

I have an apicontroller that returns List to success part of ajax function:
var inputdata = {
'InsPayInsuranceID': insPayInsuranceID
, 'InstallmentDistance': installmentDistance
, 'InsPayNumber': insPayNumber
, 'InsPayFirstInstallmentDate': insPayFirstInstallmentDate
, 'HasInsPayWitTax': insInsPayWitTax
, 'InsPayRatio': (insPayRatio > 0) ? insPayRatio : 0
}
$.ajax({
url: '/api/InstallmentApi',
type: 'Get',
datatype: 'json',
contentType: "application/json; charset=utf-8",
traditional:true,
data: inputdata,
success: function (result) {
$("#GridPan").load('#Url.Action("ReturnMyPartial", "Insurance")', result);
}
When "ReturnMYPartial" is called in success part of ajax and is sent "result"(return List from apicontroller to ajax) to it, the argument of "ReturnMyPartial" is null!
how can i solve it and get List ?
"ReturnMyPartial" controller:
public ActionResult ReturnMyPartial(List<INS_InsPaymenttDetails> myIns)//int InsuranceID , string MyInsNO)
{
//// Some Codes...
return PartialView("_MyPartial", myIns);
}
from this ajax call there is a middle piece that you haven't included. I don't know what InstallmentApi does. That is the method your ajax call is making a call to and result being empty will be from there. I would try rewriting things like this
$.ajax({
url: '#Url.Action("ReturnMyPartial", "Insurance")',
type: 'Get',
datatype: 'json',
contentType: "application/json; charset=utf-8",
traditional:true,
data: inputdata,
success: function (result) {
$("#GridPan").load(result); //I use .html but looking up .load this should work also
}
})
your controller would then take input parameters that match Inputdata
public PartialViewResult ReturnMyPartial(string InsPayInsuranceID, etc)
and on the controller you can call InstallmentApi to get the list and pass it through to the partial
var myIns = InstallmentApi(parameters);
return PartialView("_MyPartial", myIns);

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