Model:
public class JsonRequest
{
public string Data { get; set; }
}
Action:
[HttpPost]
public ActionResult Index(JsonRequest data)
{
return new JsonResult()
{
Data = string.Format("Data: {0}", data.Data), // data.Data == null here
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
AJAX:
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
JsonRequest object has an instance in Index action but it's Data property was not mapped to the passed JSON. How can I achieve this?
You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).
Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ Data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
http://api.jquery.com/jQuery.ajax/
Related
Can't figure out this simple ajax call.
The controller successfully returns the json file as it should, but is logging two zeroes as the values for both the country and amount, which are incorrect. What am I doing wrong here?
controller:
[HttpPost("search")]
public IActionResult test(int country, int amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Json("success : true");
}
jQuery:
var data = "{ 'country': 2, 'amount': 4}";
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Create a model to hold the desired values
public class TestModel {
public int country { get; set; }
public decimal amount { get; set; }
}
Update the action to expect the data in the body of the request using [FromBody] attribute
[HttpPost("search")]
public IActionResult test([FromBody]TestModel model) {
if(ModelState.IsValid) {
var country = model.country;
var amount = model.amount;
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Ok( new { success = true });
}
return BadRequest(ModelState);
}
Client side you need to make sure the data is being sent in the correct format
var data = { country: 2, amount: 4.02 };
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Reference Model Binding in ASP.NET Core
You should use JSON.stringify to convert a object into a json string. Do not try to use string concatenation to do this.
Your types for amount do not match what you are sending. A money type should probably be decimal in c#.
Return an anonymous object from the c# method as well and pass that to Json.
The content-type is incorrect, see also What is the correct JSON content type?
[HttpPost("search")]
public IActionResult test(int country, decimal amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
// return an anymous object instead of a string
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify({country: 2, amount: 4.02});
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
What am I doing wrong here?
dataType is not required so you can omit that.
4.02 is not an int so you should probably replace that with decimal
and contentType should be application/json
Thanks everyone! Got it working with your help.
It won't work after I remove [FromBody]
[HttpPost("search")]
public IActionResult test([FromBody] string data)
{
System.Console.WriteLine(data);
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify("{ 'data': 'THOMAS' }");
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
I am trying to call a controller's method by using ajax but somehow I am unable to call the method. I am sending an array type object as a parameter to post but not getting the value of the parameter on the controller, Even I send the parameter as JSON.stringify but the problem still exists.
Here is my ajax method.
$('.btn-generate-bill').on('click', function(event) {
event.preventDefault();
const billArray = [];
$('.posTable').find('tbody tr').each(function(index, elem) {
billArray.push({
ProductID: $(elem).find('.productID').text().trim(),
Quantity: $(elem).find('.qtyControl').val()
});
})
console.log(JSON.stringify(billArray));
$.ajax({
url: "/Cashier/UpdateProductQuantity",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
pDetail: JSON.stringify(billArray)
},
responseType: "json",
cache: false,
traditional: true,
async: false,
processData: true,
success: function(data) {
alert('success');
}
});
})
Here is the controller's method.
public JsonResult UpdateProductQuantity(List<Test> pDetail)
{
return Json("", JsonRequestBehavior.AllowGet);
}
public class Test
{
public int ProductID { get; set; }
public int Quantity { get; set; }
}
I think there are 2 points to be fixed :
ajax without the type will become a GET request. Put POST
try using data: JSON.stringify({ 'pDetail': billArray})
So, it becomes :
$.ajax({
url: "/Cashier/UpdateProductQuantity",
type : 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'pDetail': billArray}),
responseType: "json",
success: function (data) {
alert('success');
}
});
I would try FromBody with your controller:
[HttpPost]
public JsonResult UpdateProductQuantity([FromBody]List<Test> pDetail)
{
return Json("", JsonRequestBehavior.AllowGet);
}
You said you needed to post your billArray so your ajax request should be a post type like this:
$.ajax({
url: "/Cashier/UpdateProductQuantity",
type : 'POST', //this is the difference
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'pDetail': billArray}),
responseType: "json",
success: function (data) {
alert('success');
}
});
I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.
I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
#Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
using the following script, I am trying to access the variables being sent using data in the ajax function but I couldn't.
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '#Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC
dataType: "json", //to work with json format
type: "POST", //to do a post request
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false, //avoid caching results
data: { test: $(this).text() }, // here you can pass arguments to your request if you need
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
here is the action in the controller
public ActionResult UpdateOrder()
{
// some code
var test = Request.Form["test"];
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
I tried Request.Form["test"] but the value of it is null. how should I receive the objects of data?
Your ActionResult is GET And you have no input parameter for your ActionResult so either change those or see below:
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: /ControllerName/ActionName
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { test: comments },
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
Then within your controller:
public ActionResult UpdateOrder(string test)
{
// some code
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
Update
Remember if you want to use POST then action you are calling has to be [HttpPost] like:
[HttpPost]
public ActionResult Example()
When there is no HTTP above your ActionResult Then Its By Default Get.
The action method should be decorated with the [HttpPost] attribute. Have you used the debugger to ensure that you're actually calling in to that method?
You can always just define a view model in C# and then accept that as a parameter to your post method - Asp.MVC will parse the post data for you as long as the names of the values are the same as your model.
Have you marked your action method with [HttpPost] attribute. ?
This post helped me a lot. I did the GET but POST raise an Internal Server Error just with [HttpPost]:
[HttpPost]
public ActionResult SaveOrder(int id, string test, string test2)
So i had to set params data with JSON.stringify and it worked. My full ajax request for POST:
$.ajax({
url: "/Home/SaveOrder",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: JSON.stringify({ id:2, test: "test3", test2: "msj3" }),
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
This code works without sending parameter:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
data: { },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});
However if I want to send a parameter to the GetFee action method it doesn't work anymore:
data: { bookname : 'book1' }
And I changed my action method to accept parameter:
[HttpPost]
public ActionResult GetFee(string bookname)
You indicated:
contentType: 'application/json; charset=utf-8',
so make sure that you respect what you claimed to be sending to the server:
data: JSON.stringify({ bookname : 'book1' })
On the other hand, if you get rid of this application/json content type in your request, jQuery will use application/x-www-form-urlencoded by default and then you can simply use this:
data: { bookname : 'book1' }
Since you are specifying the datatype 'json'. So you can send only json object in request. So you need to convert data in json format.
You can do by using the JSON.stringify() method. The JSON.stringify() method converts a JavaScript value to a JSON string.
JSON.stringify(value[, replacer[, space]])
If you don't want to use JSON datatype, you don't need to convert it.
Simply use:
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: {
'bookname' : 'book1'
},
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});
As Darin Dimitrov had previously replied, you don't send your data in the format where you declare in the contentType.
In my opinion you can choose these two ways:
1.Send your parameter like a JSON string (look at Darin Dimitrov's answer) and add a [FromBody] before the input parameter, to clarify where you want to read this value.
[HttpPost]
public ActionResult GetFee([FromBody] string bookname)
2.Avoid specifying the contentType, and dataType in your ajax call, like this
$(function () {
$('#Fee').on('focus', function () {
$.ajax({
url: '#Url.Action("GetFee")',
type: "POST",
cache: false,
data: { bookname : 'book1' },
success: function (data) {
if (data.success) {
$('#Fee').val(data.message);
}
}
});
});
});