首页 > 解决方案 > 在 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>

标签: c#jqueryasp.net-mvc

解决方案


正如另一个答案告诉你的那样,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 代码,而无需您自己复制/粘贴。


推荐阅读