c# - 在 jQuery 中执行 c# 代码
问题描述
我有返回日期列表的模型函数。在我看来,我不想将类似的代码复制到 jQuery 中来填充下拉列表。
jQuery 可以执行它在 C# 中的模型函数并存储日期列表吗?
public List<string> GetAvailableDateInStrings()
{
List<string> dateList = new List<string>();
foreach(Year year in this.m_years)
{
foreach(Month month in year.GetMonths())
{
string monthString = month.MonthInEnum.ToString() + " " + year.CalendarYear.ToString();
if(year.CalendarYear == this.m_cutOffYear && month.MonthInYear <= this.m_cutOffMonth)
{
dateList.Add(monthString);
}
else if(year.CalendarYear < this.m_cutOffYear)
{
dateList.Add(monthString);
}
}
}
return dateList;
}
下面是我现在要做的。但是我想通过不在 jQuery 中创建类似的代码来减少代码重复。因此 jQuery 需要执行 C# 函数并将日期列表存储在变量中,然后填充到下拉列表中。
<script src="/Bootstrap_Sufee/assets/js/vendor/jquery-2.1.4.min.js"></script>
<script type="text/javascript">$(document).ready(function() {
$("#attendanceReportType").change(function() {
if ($("#attendanceReportType").val() == "Class Monthly") {
$("#attendanceReportYear").empty();
$("#attendanceReportYear").append("<option>May 2018</option>");
$("#attendanceReportYear").append("<option>April 2018</option>");
$("#attendanceReportYear").append("<option>March 2018</option>");
});
});</script>
解决方案
正如另一个答案告诉你的那样,Ajax 是可能的。但是有一个更简单的解决方案:在您的视图中生成所需的代码,使用ViewBag
.
在您的控制器操作中
ViewBag.MyDateList = myListOfDates;
在你看来
$("#attendanceReportType").change(function() {
if ($("#attendanceReportType").val() == "Class Monthly") {
$("#attendanceReportYear").empty();
@foreach (var myDate in ViewBag.MyDateList)
{
$("#attendanceReportYear").append("<option>@myDate.ToString("MMMM yyyy")</option>");
}
}
});
这将生成所需的 jQuery 代码,而无需您自己复制/粘贴。
推荐阅读
- html - CSS:背景过滤器弄乱了堆叠顺序
- python - OSError:[Errno 22] 无效参数:“<_io.TextIOWrapper name='C:/Users/muham/OneDrive/Desktop/test' mode='w' encoding='cp1252'>.csv”
- go - 无法在 play.golang.org 获得输入
- python - 使用 Matplotlib 绘制带有日期时间的垂直线
- c++ - 从 const 字符串参数获取非常量迭代器
- html - 内容重叠并覆盖部分
- python - .py 文件中导入的模块 pyperclip 在 Windows 命令提示符下运行时显示 ModuleNotFoundError
- php - 空记录自动插入 MySQL
- java - 将二叉树中的重复节点映射到哈希图
- android - Android RecyclerView - 父视图窃取具有负越界放置的网格项的子项的触摸事件