将列表字符串从 C# 传递到 JavaScript
Posted
技术标签:
【中文标题】将列表字符串从 C# 传递到 JavaScript【英文标题】:Passing List String from C# to JavaScript 【发布时间】:2021-12-11 18:31:51 【问题描述】:我目前正在尝试检查字符串变量的值是否为“Apple”。现在我需要将水果列表从 C# 传递给 javascript。
C#代码
List<String> fruits = new List<String>"Apple","Mango","Orange"
JavaScript 代码
$(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;
【问题讨论】:
你的问题是什么? 【参考方案1】:在 JavaScript 中使用 Ajax 调用。 像这样的:
<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>
而在 c# 的后端,是这样的:
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;
【讨论】:
以上是关于将列表字符串从 C# 传递到 JavaScript的主要内容,如果未能解决你的问题,请参考以下文章