I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId is always 0 in the controller.
I have tried this without doing JSON.stringify(data) as well with no result.
I have also tried all the different form attribute variations.
Try to use contentType as 'application/x-www-form-urlencoded':
var data = { objId: 1 };
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody] attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.
var data = { };
data["objId"] = 1; //I just wanted to show you how you can add values to a json object
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
You create a model class
public class MyModel {
public int ObjId {get;set;}
}
Your controller should expect one of these
[HttpPost]
public JsonResult PassIntFromView([FromBody] MyModel data)
{
//DO stuff with int here
}
JSON has a preference for strings not integers. You are better off to use JSON.stringify(data) to parse to your controller, convert that to a integer in the controller, then parse the string that was returned as:
var data = { objId: 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',//asp.net - url: 'api/controllerName/controllerFunction'
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
var result = JSON.parse(data);
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Try this:
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: data,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Your controller:
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//DO stuff with int here
}
Js
var data = { "objId": 1};
$.ajax({
url: "ControllerName/PassIntFromView",
data: data,
type: "POST",
dataType: 'JSON',
success: function(data.result!=null) {
console.log(data.result);
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
I got it working like this
let numberFour = JSON.stringify(4);
$.ajax({
.......
.......
data: numberFour,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
......
........
});
Related
I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.
I am really new to Javascript, Ajax and JSON. I have the following code:
$(document).ready(setInterval(function () {
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("GetBase64Image","Home")',
contentType: 'application/json',
datatype: "json",
success: function(data)
{
alert(data.imagefilename);
displayImage(data);
}
})
},5000));
[HttpGet]
public ActionResult GetBase64Image()
{
if (ImageIndex==ImageData.Length) ImageIndex=0;
string fname = Path.GetFileName(ImageFileNames[ImageIndex]);
return Json(new { base64image = ImageData[ImageIndex++], imagefilename=fname }
, JsonRequestBehavior.AllowGet);
}
}
I do see the GetBase64Image is being called every 5 seconds but the alert only displays the value from first call to the method. What am I doing wrong.
Thanks.
public JsonResult GetPrice(List<int> modelValues)
{
List<int> model = new List<int>();
try
{foreach(var d in modelValues)
model.Add(d);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
function GetDetail() {
var jsonUrl = Home/GetPrice";
$.ajax({
cache: false,
url: jsonUrl,
type: "POST",
data: "{}",
contentType: "application/json",
dataType: 'json',
async: true,
success: function (data) {
},
error: function (x, t, m) {
}
});
I want my values present in model to display in label.It should be done by binding data using ajax call. Can someone please suggest me a solution? Label id="name" in html file.
I have tried like this but could not get array list. It returns 'null'
var data=[];
data[0] = '1';
data[1] = '2';
$.ajax({
url: '#Url.Action("AddFrequencyWeekly", "Plannar")',
type: "POST",
data: { data: data },
dataType: 'json',
success: function (data) {
alert("Record Updated Successfully");
}
});
my model class code following
public JsonResult AddFrequencyWeekly(string[] data)
{
}
data value says 'null'
please help me?
var datas = { data0: '1',
data1: '2' };
$.ajax({
url: '#Url.Action("AddFrequencyWeekly", "Plannar")',
type: "POST",
data: datas,
dataType: 'json',
success: function (data) {
alert("Record Updated Successfully");
}
});
Its the way you are expecting to recive the data in the action method,
try
public JsonResult AddFrequencyWeekly(IEnumeable<string> data)
{
}
I tried to find a workaround all morning(browsered every related post in SO & did several experiments myself), but failed.
Here's the Server code:
Controller:
[HttpGet]
public JsonResult Test(Entity e)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
Entity:
public class Entity
{
public string A { set; get; }
public string B { set; get; }
}
With Client code:
var e = {
A: "1",
B: "2"
};
$.ajax({
url: "/Home/Test",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(e)
// data: e
});
I get:
With Client Code:
var e = {
A: "1",
B: "2"
};
$.ajax({
url: "/Home/Test",
//contentType: "application/json; charset=utf-8",
dataType: "json",
//data: JSON.stringify(e)
data: e
});
I get:
Hope to find a answer, coz application/json is more useful
EDIT
The parameters can be passed correctly when i change the protocal to POST.
Here's the new question: Why not GET?? coz the converted request querystring doesnt meet mvc3's need??
EDIT2
http://forums.asp.net/t/1766534.aspx/1
It seems that all issues are on the GET method. GET shouldn't pass complex params?? That's very weird if u are fan of restFUL
Try specifying the request type (although it defaults to GET anyway):
var e = {
A: "1",
B: "2"
};
$.ajax({
type: "GET",
url: "/Home/Test",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(e)
});
or, try using a POST request and decorate the JsonResult action method with the [HttpPost] attribute:
[HttpPost]
public JsonResult Test(Entity e)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
then
$.ajax({
type: "POST",
url: "/Home/Test",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(e)
});