Lambda fetching multiple records with contains query returns empty - ajax

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);
}
});

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.

Display all data fetched, api rest using __next

I need to fetch all data from an xml link but I couldn't as it displays only 300 rows, so I found a solution that says I should use __next, I have the code below but it doesn't work, in the console I get the next url but the items (TaskName) of the first page. I want to get the TaskName(s) of the next pages.
window.addEventListener('load',function() {
$.ajax({url: _spPageContextInfo.siteAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks",
method: "GET",
dataType: "json",
headers: {Accept: "application/json;odata=verbose"},
success: function(data) {
var dataResults = data.d.results;
if (data.d.__next) {
url = data.d.__next;
console.log("url: "+url);
}
$.each(dataResults, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
}});
});
I found a solution, here the code is:
function GetListItems(){
$.ajax({
url: urly,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data){
response = response.concat(data.d.results);
if (data.d.__next) {
urly = data.d.__next;
GetListItems();
}
$.each(response, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
},
error: function(error){
}
});
}

Binding json response to label

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.

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

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