Binding json response to label - ajax

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.

Related

Ajax post zero to controller

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.

ajax POST int parameter in asp.net core

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",
......
........
});

Passing HttpPostedFileBase and other variables in ajax POST to mvc controller

I have been trying to post a file and some variables to my controller action using ajax, but I am getting null parameters for both of my variables.
Below is my ajax call
$("#btn-upload").on("click", function () {
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
var Data = formData+"&rows="+rows;
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: Data,
cache: false,
contentType: false,
processData: false,
success: function (result) {
if (result=='True') {
$(".alert-success").show();
}
else {
$(".alert-danger").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".alert-danger").show();
},
});
});
and my controller action is
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile, int? rows)
{
var excelUtility = new ExcelUtilityService();
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}
If I pass only the file parameter in my ajax call it works fine but when I try to do it with multiple parameters e.g 'rows' in my code, both of the parameters become null in my controller action while post.
In order to add values to a FormData object, you need to use .append().
Modify your script to
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
Using the script modification from Stephen:
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
If linking to parameters directly doesn't work with the formData.append() method above, I would recommend accessing them via:
Request["key-used-to-append"]
Example with your controller (rows variable assignment):
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile)
{
var excelUtility = new ExcelUtilityService();
var rows = Request["rows"];
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}

Lambda fetching multiple records with contains query returns empty

I have this code:
public JsonResult EkranBilgiListele(List<int> ids)
{
dbReklam db = new dbReklam();
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.sektorID));
return Json(secilenEkranlar);
}
And an AJAX call:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (data) {
console.log('---->' + data.ekranAd);
},
dataType: "json",
traditional: true
});
However, using breakpoints and results view always returns 'empty' and the console returns 'undefined'
Really sorry I wrote wrong query!
Writing right one.
public JsonResult EkranBilgiListele(List<int> ids)
{
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.ekranID));
return Json(secilenEkranlar);
}
ajax code, changed a little bit:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (secilenEkranlar) {
$.each(secilenEkranlar, function (i, ekranlar) {
console.log(ekranlar.ekranAd);
});
},
error: function (ex) {
alert('İlçeler Çekilemedi.' + ex);
}
});

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources