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.
Related
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"));
}
View:
<script type="text/javascript">
$(document).ready(function () {
$("#OriginInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AjaxMethod","MyUrl")', type: "POST", dataType: "json",
data: { id: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.id };
}));
}
});
},
minLength: 2
});
Controller
public static List<PostalCodeModel> ListOfPostalCode;
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod(string x)
{
x = Request.QueryString["term"];
var locations = ListOfPostalCode.Where(r => x != null && (r.City.StartsWith(x) || r.State.StartsWith(x) || r.Zip.StartsWith(x) || r.Country.StartsWith(x))).Take(25).Select(r => new { id = r.ToString(), label = r.ToString(), name = r.ToString() });
return Json(locations, JsonRequestBehavior.AllowGet);
}
Model
public class PostalCodeModel
{
public PostalCodeModel(string c, string s, string z, string o)
{
City = c;
State = s;
Zip = z;
Country = o;
}
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public override string ToString()
{
// trim to remove unnecessary spaces
return City.Trim() + ", " + State.Trim() + ", " + Zip.Trim() + ", " + Country.Trim();
}
Every time I make this call in my autocomplete box, x returns null in my Controller and thus does not parse any info from the list of postal codes. Not included is the query that initializes my complete list of postal codes in Controller (which is 190000 or so items large), but it seems to work fine.
I assume the main issue is with my ajax in the view not passing the "OutputText" box to the request/response, but I can't seem to find the problem when searching elsewhere. Thanks for any and all help; just started using JavaScript a week ago.
In your ajax method you are sending the wrong data. It should be like this.
$.ajax({
url: '#Url.Action("AjaxMethod", "MyUrl")',
type: "POST",
data: { term: request.term },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.id };
}));
}
});
Also you don't need to get parameter with Request.QueryString["term"];
Change
public JsonResult AjaxMethod(string x)
to
public JsonResult AjaxMethod(string term)
Also don't forget to null check term.
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();
}
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);
}
I have following javascript method to pass json object with some object and an arry to my controller. Json objects are assigned properly but array is empty what am I doing worn.
function setData() {
var quotation = {
ID : 0,
Number : "",
AccountName : getAccount(),
CurrencyID : getCurrencyID(),
Date: getQuoteDate(),
ExchangeRate :getExchangeRate(),
Percentage : getPercentage(),
PriceListId: getPriceListId(),
}
quotation.Items = [];
$.each(this.selectedItem.items, function (index, qitem) {
var Item = {
ID: 1,
ItemNumber:"lcfe"
};
quotation.Items.push(Item);
});
$.ajax({
url: '#Url.Action("CreateQuotation", "Main")',
data: quotation,
contentType: "application/json; charset=utf-8",
type: 'GET',
success: function (dat1a) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert("Status: " + XMLHttpRequest); alert("Error: " + errorThrown);
}
});
}
My Model classes.
public class Quotation
{
public long ID { get; set; }
public string Number { get; set; }
public List<QuotationItem> Items { get; set; }
//....
}
public class QuotationItem
{
public long Id { get; set; }
public string ItemNumber { get; set; }
}
Here is result I seen in debug.
I can see 2 objects are added in List but their vlaues ID, ItemNumber are not assigned?
Any idea?