Cannot pass a object to a controller method with popup - javascript

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

Related

.Net core - Ajax post does not pass variables to controller method

When I set a breakpoint on LoadReport, every parameter is null. For some reason the values are not binding to the parameters with the same name.
Javascript/AJAX
$('#savedCriteria').on('change', function () {
var criteriaSelected = $('#savedCriteria option:selected').text();
var data = { actionName: "Daily", reportInput: "ReportDaily", reportCriteria: criteriaSelected };
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: "application/json; charset=utf-8",
url: '#Url.Action("LoadReport", ViewContext.RouteData.Values["Controller"].ToString())',
success: function (data) {
if (data.success) {
alert("Test");
} else {
alert("Test Not Successful");
}
}
});
});
Controller
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Default method type is HttpGet, you need to set it to HttpPost.
[HttpPost]
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Also keep in mind that with your ajax call you can not use RedirectToAction. You need something like this:
[HttpPost]
public ActionResult LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
Return Json(Url.Action(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
And in your ajax call:
success: function (data) {
window.location.href = data;
}
UPDATE: you also need to create a POCO object and add that to the HttpPost method as parameter instead of separate parameters. Also [FromBody] attribute is needed.
POCO:
public class Data
{
public string actionName { get; set; }
public string reportInput { get; set; }
public string reportCriteria { get; set; }
}
Controller:
[HttpPost]
public JsonResult LoadReport([FromBody]Data data)
{
var reportObject = Activator.CreateInstance(Type.GetType(data.reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(data.reportInput);
return Json(Url.Action(data.actionName, "Reports"));
}

ASP.NET MVC ajax post function sending null values

My apologies if there is an answer already out there for this, I could not find one.
I have an ajax function that posting data to a controller, but some of the data being sent have null values. Here is my setup:
I have 3 parameters being sent to the controller: data, rptnew and recid.
The data parameter is a string containing db column names and data.
rptnew and recid only contain one value.
var data = "{'DATEWORKING':'" + $('#HEADER-DATEWORKING').val() +
"','TRAYS':'" + $('#TRAYS').val() +
"','M26850':'" + $('#INCOMINGMAIL5').val() +
"','M26860':'" + $('#INCOMINGMAIL6').val() +
"','X26930':'" + $('#INCOMINGMAIL9').val() +
"','T26920':'" + $('#INCOMINGMAIL8').val() +
"','C2501':'" + $('#INCOMINGMAIL1').val()+ "'}";
rptnew = '0';
recid = '2347';
function post:
function postdata(data, section, recid, rptnew) {
$.ajax
({
type: 'POST',
url: 'UpdateDB_IR’,
async: false,
data: ( data, rptnew, recid ),
dataType: "json",
success: function (result) {
if (result) {
alert("Data Saved Successfully");
afterpostfunctions();
}
else
alert(result);
},
error: function (result) {
alert("Error Occured, Try Again");
console.log(result);
}
});
Controller:
public ActionResult UpdateDB_IR(DATABASE_RECORDS dbData, string rptNew, string recId)
The problem:
dbData contains the columns and values from the variable data.
rptNew does not contain the value from rptnew.
recId does not contain the value from recid.
If I stringify the data like:
JSON.stringify({ dbData: data, rptNew: rptnew, recId: recid });
dbData does not contain the values from data.
rptNew contains the value from rptnew.
recId contains the value from recid.
I’m at a loss on how to send all values over correctly to the controller. Any suggestions?
database class:
namespace REPORTSYS.Models
{
using System;
using System.Collections.Generic;
public partial class DATABASE_RECORDS
{
public int CBAD_ID { get; set; }
public int TRAYS { get; set; }
public int M26850 { get; set; }
public int M26860 { get; set; }
public int X26930 { get; set; }
public int T26920 { get; set; }
public int C2501 { get; set; }
}
}
function postdata(data, section, recid, rptnew) {
$.ajax
({
type: 'POST',
url: 'UpdateDB_IR’,
async: false,
data: { dbData : data, rptNew : rptnew, recId : recid },
dataType: "json",
success: function (result) {
if (result) {
alert("Data Saved Successfully");
afterpostfunctions();
}
else
alert(result);
},
error: function (result) {
alert("Error Occured, Try Again");
console.log(result);
}
});
Send data with key to the controller. As modified in above function.
Try this on data
data: { dbData: data, rptNew: rptnew, recId: recid }
Don't use stringify.

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

sending data from js over wire to the controller

Inside js function I'm creating javascript object which I then send to the mvc controller using ajax
var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(ab),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
on server side I have
[HttpPost]
public ActionResult DoSomething(string ab)
{
... ab is always null
}
I'm guessing that I should using some other data type as expected in controller method instead of string?
You need to use id and name in your action method
[HttpPost]
public ActionResult DoSomething(int id, string name)
{
//code
}
Try this:
JS:
var ab = { Id: 100, Name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
data: JSON.stringify({ ab: ab }),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
Controller:
[HttpPost]
public ActionResult DoSomething(YourClass ab)
{
. . .
}
Model:
public class YourClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Make a class of the JSON object, peg it as Serializable
[Serializable]
public class SomeClass
{
public int id { get; set; }
public string name { get; set; }
}
In your controller, you can now accept this as:
[HttpPost]
public ActionResult DoSomething([FromBody] SomeClass someclass){
// code
}
var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
// what if you pass data like this
data: JSON.stringify({ab:ab}),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
If you want to send { id: 100, name: "abc" } as a string to the controller you need to change the data in ajax call to
data: JSON.stringify({ab:ab}),
if you want to send id and name as separate paramamters change your controller to
public ActionResult DoSomething(string id, string name)
{
}
and your ajax call data to
data: '{ "id":" 100 ","name":"abc" }',

Categories

Resources