I have a method in an MVC controller that queries a database, and returns a JSON object. It requires an ajax call to give it a date to query the database, however, in my current setup I'm getting null passed to the controller.
Here is my ajax request:
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetChartData", "Plot")',
dataType: 'json',
data: '04-15-2019 15:49:00',
success: function (result) {
console.log(JSON.parse(result)
}
});
}, 10000)
Here is my controller:
[HttpPost]
public JsonResult GetChartData(string timeStamp)
{
string output = queryDatabase(timeStamp);
string test = new JavaScriptSerializer().Serialize(output);
return Json(output, JsonRequestBehavior.AllowGet);
}
Now, when I put a breakpoint after the queryDatabase call, the timeStamp variable is null, what am I doing wrong?
Thanks!
Try something like this
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetChartData", "Plot")',
dataType: 'json',
data: {timeStamp: '04-15-2019 15:49:00'},
success: function (result) {
console.log(JSON.parse(result)
}
});
}, 10000)
});
And in the controller:
[HttpPost]
public JsonResult GetChartData()
{
var timeStamp = Request["timeStamp"];
var output = queryDatabase(timeStamp);
var test = new JavaScriptSerializer().Serialize(output);
return Json(output, JsonRequestBehavior.AllowGet);
}
Add [FromBody]-attribute to force controller to read a simple type from the request body:
using System.Web.Http;
[HttpPost]
public JsonResult GetChartData([FromBody]string timeStamp)
{
string output = queryDatabase(timeStamp);
string test = new JavaScriptSerializer().Serialize(output);
return Json(output, JsonRequestBehavior.AllowGet);
}
When you use Post type and dataType JSON on your Ajax call u need to pass data in this format {title:data} in ur case it will be
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetChartData", "Plot")',
dataType: 'json',
data: {timeStamp: '04-15-2019 15:49:00'},
success: function (result) {
console.log(JSON.parse(result)
}
});
}, 10000)
In your controller it will automatically catch data in argument. Provided just double check ur URL in Ajax call
Related
I'm trying to get some string from my Controller and use it in the View.
The ActionResult works like this:
public ActionResult GetSymbols()
{
string result = "SVG-String";
return Content(result);
}
This result is will be a svg-formatted string and should be shown in my svg-drawing, at the end.
I tried to call this controller-Action, using JavaScript and I could reach the Controller but how could I use the String? I couldn't see any result, so what is the rigth way to get the returned string into a variable?
The last try was like this:
$(document).ready(function () {
$.ajax({
url: "/Symbols/GetSymbols/",
method: "GET",
async: false,
data: "",
dataType: "string",
success: function (data) { alert(data); }
});
});
How about this one,
Change your Controller return type to Json
[HttpGet]
public JsonResult GetSymbols()
{
string result = "SVG-String";
return Json(result, JsonRequestBehavior.AllowGet);
}
And your javascript be like,
$(document).ready(function () {
$.ajax({
method: "GET",
url: "/Symbols/GetSymbols/",
async: false,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (response) {
console.log(response);
}
});
});
I want to change(calculate) a textboxs' value on ajax keypress event but the controller ActionResult is not receiving any value to calculate(receiving null)
<script>
$('#TotDiscnt').keypress(function () {
//var data = $('#totDiscnt').val();
$.ajax({
type: 'Post',
url: '/Whatever/Discount',
data: $('#totDiscnt').val(),
success: function (response) {
$('#TotPurAmt').val(response);
}
});
});
</script>
On controller
public ActionResult Discount(string text)
{
// calculation
return Json(sum, JsonRequestBehavior.AllowGet);
I tried as
data: { text: request.term },
while i do that the the ajax call is not calling the controller method.And one more thing how can i send two double value as a parameter to the ActionResult method form an ajax call as
<script>
$('#TotDiscnt').keypress(function () {
//var data = $('#totDiscnt').val();
$.ajax({
type: 'Post',
url: '/Whatever/Discount',
data: {num1:$('#totDiscnt').val(),
num2:$('#Discnt').val() },
success: function (response) {
$('#TotPurAmt').val(response);
}
});
});
and then receive as double value in parameter like
public ActionResult Discount(double num1, double num2)
{
//calculation
return Json(sum, JsonRequestBehavior.AllowGet);
Yes you can add event either keyup or keypress. You can change your code slightly.
<script>
$('#TotDiscnt').keypress(function () {
//var data = $('#totDiscnt').val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8', //send type of data to sever
dataType: 'json', //retrun type of data from server
url: '/Whatever/Discount',
data: JSON.stringify(text:$(this).val()),
// data: $('#totDiscnt').val(),
success: function (response) {
$('#TotPurAmt').val(response);
}
});
});
Here your controller should be as.
public ActionResult Discount(string text)
{
// calculation
return Json(sum, JsonRequestBehavior.AllowGet);
}
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
For more detail please visit official site click me
Please let know in comment is it working or not.
To send multiple value from an ajax call to ActionResults' parameter:
Script:
<script>
$(document).ready(function () {
$('#btnCalculate').click(function () {
$.ajax({
type: 'Post',
url: '/Sales/Calculate',
data: { num1: $('#txtNum1').val(), num2: $('#txtNum2').val(),//so on.... },
success: function (response) {
$('#txtSum').val(response)
}
});
});
});
</script>
and on controller:
public ActionResult Calculate(int num1, int num2)
{
int sum = 0;
sum = num1 + num2;
return Json(sum, JsonRequestBehavior.AllowGet);
}
Data doesn't passing to controller, always null
My script in view:
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "json": JSON.stringify(selected) },
error: function () {
alert("Error!");
}
});
}
My home controller method:
[HttpPost]
public IActionResult DeleteRecords(string AllId)
{
return null;
}
send ajax request data like below,
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
and receive the data in action like
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
It need to pass the action. Hope it helps to you.
with the code in your question, try below to get the json
System.Web.Context.Current.Request.Form["json"]
if you want some more graceful stuff, you need to put FromBody attribute in your parameter signature
DeleteResults([FromBody] string json)
Name your property in the Post the same as your method so that the automatic binding picks it up. - Turns out this doesn't matter for single object.
The data Object you were creating was not parse-able by .net, use JSON.stringify directly for the data payload.
Note: The change in Home controller since you are passing an array of string.
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
}
For your home controller method:
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);
I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.