Passing List String from C# to JavaScript - javascript

I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}

Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}

Related

.NET Core Pass Variable to Javascript from C#

I'm trying to pass two arguments to the Authorization.js file. It is used to search in the variables that I sent from Index.cshtml file.
Here at the end of the Index.cshtml file
<script src="~/AreasFolder/Authorization/js/Authorization.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var fork = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Repository.RoleTreeRepository(_configuration).TaskItemRolsuzGetir()))';
sayfaGruplariArray = JSON.parse(fork);
var exec = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Helpers.UserHelper(_roleManager).GetRoles()))';
rollerArray = JSON.parse(exec);
$("#sayfaAraTable").toggle(false);
$('#sayfaAraTextbox').keyup(function () {
sayfalariFiltrele(true);
});
$("#sayfaGrubuAraTable").toggle(false);
$('#sayfaGrubuAraTextbox').keyup(function () {
sayfaGruplariniFiltrele(true);
});
$("#kullaniciAraTable").toggle(false);
$('#kullaniciAraTextbox').keyup(function () {
kullanicilariFiltrele(true);
});
$("#rolAraTable").toggle(false);
});
In the controller, string ItemName returns NULL from Authorization.js:
Finaly, Authorization.js file:
var sayfaGruplariArray;
var rollerArray;
function sayfalariFiltrele(isAutoComplete) {
var content = $('#sayfaAraTextbox').val();
if (content.length == 0 && isAutoComplete) {
$("#sayfaAraTable").toggle(false);
//$("tr:not(:first)", "#sayfaAraTable").remove();
}
else {
//$("tr:not(:first)", "#sayfaAraTable").remove();
$.ajax({
url: "/Authorization/Item/SayfaAra",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
itemName: content
}),
beforeSend: function (xhr) {
//jQuery.blockUI({ message: 'Lutfen bekleyiniz', baseZ: 2000 });
$('#sayfaAraTextbox').addClass('textboxLoadinggif');
},
success: function (result) {
if (result.ErrorCode == "0") {
$("#sayfaAraTable").toggle(true);
var html = "";
var sayfalarArray = result.SayfaListesi;
if (sayfalarArray.length > 0) {
html += "<tr>";
html += "<th>İşlem adı</th>";
html += "<th>Açıklama</th>";
html += "<th>URL</th>";
html += "<th>Menüde görünsün</th>";
html += "<th style='width:1%'></th>";
html += "</tr>";
}
for (i = 0; i < sayfalarArray.length; i++) {
html += "<tr id='sayfaTr" + sayfalarArray[i].AuthorizationItemKey + "'>";
html += "<td>" + sayfalarArray[i].ItemName + "</td>";
html += "<td>" + sayfalarArray[i].Description + "</td>";
html += "<td>" + sayfalarArray[i].MenuLinkUrl + "</td>";
html += "<td>" + sayfalarArray[i].DisplayInMenu + "</td>";
html += "<td nowrap><a href=\"javascript:SayfaBilgisiniGetir(" + sayfalarArray[i].AuthorizationItemKey + ")\"title='Güncelle'><i class='fa icon-pencil fa-2x'></i></a> <a href='javascript:SayfaSilUyari(" + sayfalarArray[i].AuthorizationItemKey + ")' title='Sil'><i class='fa icon-trash fa-2x'></i></a></td>";
html += "</tr>";
}
//$("#sayfaAraTable").append(html);
$("#sayfaAraTable").html(html);
}
else {
$("#sayfaAraTable").toggle(false);
toastr.warning(result.Result, "Uyarı", { timeOut: 3000 });
}
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
},
failure: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script failure: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
},
error: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script error: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
}
});
}
}
Any idea? What cause this problem? Thank you in advance.
You should use [FromBody] to get the json format data. Change it like below:
$.ajax({
//...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(content),
//...
})
Controller:
public ActionResult SayfaAra([FromBody]string itemName)

GET Method always receives null value

I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});

How to pass return value in Javascript to the Controller

This is my Javascript code that gets the value from the query string
function getUrlVars() {
var name = [], hash;
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
hash = url[i].split('=');
name.push(hash[0]);
name[hash[0]] = hash[1];
var hid =hash[1];
return pid;
}
}
var hid = getUrlVars()['pid'];
This is my URL: http://localhost:33454/Product?pid=1
[HttpGet]
[Route("api/product/getproducts/{pid}")]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Ok(selectProducts);
}
This is my AJAX for printing the list to the html
var $view = $('.table')
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/{pid}',
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Are there any issues with my code. Sorry, I know this might be a really simple question to you all. I'm new to programming.
Thanks in advance.
The API URL is not being constructed properly for the AJAX call.
//...code omitted for brevity
var hid = getUrlVars()['pid'];
//...
var $view = $('.table');
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/' + hid, //<<<<
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Change your code to this.
[HttpPost]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Json(selectProducts, JsonRequestBehavior.AllowGet);
}
And this should be:
Replace {ControllerName} with your controller's name with no curly braces
For example: url: '/Clients/Details'
var $view = $('.table')
$(function () {
$.ajax({
type: 'POST',
url: '/{ControllerName}/Product',
data: JSON.stringify({ pid: hid}),
dataType: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});

How to pass values to asp pages from javascript?

I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}

showing error that mouse_id is undefined while implementation in javascript

Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.

Categories