How to pass Array from jQuery Ajax to the MVC 5 Action? - javascript

I try to pass my grid Data from jQuery to the MVC Action via Ajax.
I have a button "Save" on my page, and this is jQuery code for click:
var result = [];
$('#btnSave').click(function () {
$('#tblMatters tbody tr.mattersRow').each(function () {
var item = {};
if ($(this).find('td.qbmatter > div.dropdown').length > 0) {
item.QBMatter = $(this).find('td.qbmatter > div.dropdown > a').text();
} else {
item.QBMatter = $(this).find('td.qbmatter').text();
}
item.Hours = $(this).find('td.hours').text();
item.Person = $(this).find('td.person').text();
if ($(this).find('td.rate > div.dropdown').length > 0) {
item.Rate = $(this).find('td.rate > div.dropdown > a').text();
} else {
item.Rate = $(this).find('td.rate').text();
}
item.Amount = $(this).find('td.amount').text();
result.push(item);
});
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: { 'Matters': result },
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) { alert("Success!"); },
error: function () { alert("An error has occured!!!"); }
});
});
I checked the result array and it's correct. It contains every value that should be.
In my HomeController I have the following model for my data:
public class QBMatter
{
public string QBDescription { get; set; }
public string Person { get; set; }
public decimal Hours { get; set; }
public int Rate { get; set; }
public decimal Amount { get; set; }
}
And the following Action:
public ActionResult SaveQBMatter (QBMatter[] Matters)
{
DBAccess dba = new DBAccess();
int QBMatterID = 0;
foreach (QBMatter qb in Matters)
{
dba.InsertQBMatter(qb.QBDescription, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID);
}
return RedirectToAction("Home", "Index", "Home");
}
But I always getting the "An error has occured!!!" result... And I even don't get to the action, so error somewhere on the ajax level...
What I'm doing wrong?

You need to stringify the data while sending it.
Try:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success!");
},
error: function () {
alert("An error has occured!!!");
}
});

Related

model is null when passed to ActionResult

Can anyone spot why my model would be null when it's passed to the controller? I put an alert in the ajax call to check the value there and it look correct, but a breakpointon the 1st line on the controller ActionResult shows it is null.
thanks in advance
ajax call
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems",
dataType: 'json',
data: { 'model': _model, 'id': mId },
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
Controller
[HttpPost]
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")](CreateLPathModel _model, string id)
{
List<ModuleItems> items = _model.SelectedModuleList;
ModuleItems itemToDelete = new ModuleItems();
foreach (var item in items)
{
if (item.ArticleGuid == id)
{
itemToDelete = item;
}
}
_model.SelectedModuleList.Remove(itemToDelete);
itemToDelete.isSelected = false;
_model.SelectModulesList.Add(itemToDelete);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectModulesList")).ToList())
ModelState.Remove(key);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectedModuleList")).ToList())
ModelState.Remove(key);
return PartialView("~/Views/Partials/LearningPaths/_CreateLPath.cshtml", _model);
}
You are serializing your form and send as a property to your data model. In order to solve your problem, you can set data property with your _model variable and send your mId variable as query string :
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems?id=" + mId,
dataType: 'json',
data: _model,
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
It can be done with:
Create a class with below structure:
public class RootObject
{
public CreateLPathModel _model {get; set;}
public string id {get; set;}
}
Then Controller method will be:
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")]([FromBody] RootObject obj)
{
// use Obj._model etc
}
and make sure while passing data in the AJAX call:
data: JSON.stringify({ 'model': _model, 'id': mId });

Cannot pass a object to a controller method with popup

From an ajax call I get some data which I want to pass to another window in a button click. I receive the data successfully but when that data is passed, in controller methods parameter is receiving the value as null.
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Get',
url: '/Reports/SalesInAmount' + '?toDate=' + data.toDate + '&fromDate=' + data.fromDate + '&customerId=' + data.customerId,
data: data,
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
</script>
in controller
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
the model
public class SalesInAmount
{
public DateTime SalesDt { get; set; }
public int SalesSl { get; set; }
public int CustomerSupplyId { get; set; }
public string CustomerSupplyNm { get; set; }
public double TotalSalesByCustomer { get; set; }
public double TotalDiscount { get; set; }
public double TotalVat { get; set; }
public double TotalSales { get; set; }
public List<SalesInAmount> List { get; set; }
}
Try this ,
Simplify Your Data Set ,
var Param1= $('#ID').val();
var Data = JSON.stringify({ Data1 : Param1, . . });
Ajax
$.ajax({
url: '#Url.Action("Action_Name", "Controller_Name")',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: Data,
cache: false,
success: function (data) {
});
}, error: function (request, status, error) {
}
});
}
Controller
public JsonResult Action_Name(string Data1 , . . )
{
return Json(Some_Json);
}
Note : this Controller Return Json Result , It depends on requirement .
You need to stringify the javascript object before pass as the parameter , JSON.stringify() is the function in javascript
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Post',
url: '/Reports/SalesInAmount',
data: JSON.stringify(data),
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
Make sure you have given same name of variable as you modal class SalesInAmount.
[HttpPost]
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}

Passing an object with values from View to ActionResult using ajax

I want to send an object from view to controller, ajax hits the action result but data is not being delivered to action result
View:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: '{obj' + JSON.stringify(obj) + '}',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
Model:
public class QAViewModel
{
public string C { get; set; }
public string EE { get; set; }
public string MD { get; set; }
public string ME { get; set; }
public string PD { get; set; }
public string RT { get; set; }
public string SEA { get; set; }
public string SED { get; set; }
}
Controller:
Editing as a good point was raised:
In the post you can just pass the full object like so:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: obj,
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
If you want to stick with json then modify your ajax call accordingly (you error was in the way you were building the data property:
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: JSON.stringify({obj: obj}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
Also, depending on what you are doing with the result you may need to flip your controller actions to return JsonResult (Ignore if you are doing something such as returning a partial view to load):
[HttpPost]
public JsonResult Whatever(QAViewModel obj)
{
return Json(whatever, JsonRequestBehavior.AllowGet);
}

How to call Controller method of type HttpPost from Jquery ajax call

I am trying to call a controller function in MVC called UpudateFingerprintStatus from my jquery script. This is a PUT call because i'm updating the status of the desired object. I'm getting a 404 error when i'm trying to call this method.
Here is my JS code:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
$.ajax({
type: "POST",
url: "/Tools/FingerprintTool/UpdateFingerprintStatus",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
}),
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
And here is my Controller method:
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}
Any help would be greatly appreciated!
When we send post , put request it sends complex data type in body so to bind that complex data you need to create class in which all properties should have same name as you sending from front-end.
public class FingerprintStatus{
public string UserId { get; set; }
public int StatusId { get; set; }
public int FingerprintId { get; set; }
public bool IsDeleted { get; set; }
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(FingerprintStatus model)
{
var response = _driver.UpdateFingerprintGrantById(model.UserId, model.FingerprintId, model.IsDeleted, model.StatusId);
return Json(response.Note);
}
This should work:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
var domain = window.location.protocol + "//" + window.location.host;
var url = domain + "/Tools/FingerprintTool/UpdateFingerprintStatus";
var dataContract = {
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
};
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: dataContract,
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}

Ajax call hits with null values

I have a array and I get data from the array and going to pass it to the controller through ajax call.
But the problem is it hits the controller side with all the null values.(Data not passes,null passes )
Client Side Code
for (var j = 0; j < NewsGlobalArray.length; j++) {
var NewsRequestModel = {
DESCRIPTION: NewsGlobalArray[j]['DESCRIPTION'] // news description comes here.i checked it with console.log
}}
$.ajax({
url: $('#addNewsRequest').val(),
type: "POST",
data: { newsRequest: NewsRequestModel },
dataType: "json",
success: function (referenceNo) {
//success
}
});
}
My Controller
[HttpPost]
public JsonResult AddNewsRequest(NewsRequestModel newsRequest) // hits here with null values
{
//Some coding goes here.
}
My Model
public class NewsRequestModel
{
public int NEWSREQUESTID { get; set; }
public string DESCRIPTION { get; set; }
}
Try this: just add traditional:true in ajax call
$.ajax({
type: "POST",
url: $('#addNewsRequest').val(),
data: JSON.Stringify({ newsRequest: NewsRequestModel }),
dataType: "json",
traditional:true,
success: function (res) {
//do something
}
});
I think you need to this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
then pass myObject to ajax call and get on controller by name.

Categories

Resources