首页 > 解决方案 > Razor Pages 保存日历中的点击日期

问题描述

我正在使用 Asp Core 中的 Razor 页面 Web 应用程序,我正在使用此代码生成带有 html 和 java 脚本的日历。当我单击日历中的某一天时,我被重定向到一个页面。在该页面中,我需要根据用户选择的日期从我的模型类中检索一些数据。

有什么方法可以保存单击日期以在我的 Razor Page 课程中使用?

这是js代码:

function myFunction() {
    function calendar() {
        var padding = "";
        var totalFeb = "";
        var i = 1;
        var current = new Date();
        var cmonth = current.getMonth();
        var day = current.getDate();
        var tempMonth = month + 1; //+1; 
        var prevMonth = month - 1;
 
        if (month == 1) {
           if ((year % 100 !== 0) && (year % 4 === 0) || (year % 400 === 0)) {
               totalFeb = 29;
           } else {
               totalFeb = 28;
           } 
        }
 
        var monthNames = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
        var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"];
        var totalDays = ["31", "" + totalFeb + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];

        var tempDate = new Date(tempMonth + ' 1 ,' + year);
        var tempweekday = tempDate.getDay();
        var tempweekday2 = tempweekday;
        var dayAmount = totalDays[month];

        while (tempweekday > 0) {
            padding += "<td class='premonth'></td>";
            tempweekday--;
        }

        while (i <= dayAmount) {
            if (tempweekday2 > 6) {
                tempweekday2 = 0;
                padding += "</tr><tr>";
            }

            if (i == day && month == cmonth) {
               padding += "<td class='currentday' onclick='redirect();' onMouseOver='this.style.background=\"#00FF00\"; this.style.color=\"#FFFFFF\"' onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#00FF00\"'>" + i + "</td>";
            } else {
                padding += "<td class='currentmonth' onclick='redirect();' onMouseOver='this.style.background=\"#00FF00\"' onMouseOut='this.style.background=\"#FFFFFF\"'>" + i + "</td>";
            }
            tempweekday2++;
            i++;
        }

        var calendarTable = "<table class='calendar'> <tr class='currentmonth'><th colspan='7'>" + monthNames[month] + " " + year + "</th></tr>";        
        calendarTable += "<tr class='weekdays'>  <td>Sun</td>  <td>Mon</td> <td>Tues</td> <td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
        calendarTable += "<tr>";/        calendarTable += padding;
        calendarTable += "</tr></table>";
        document.getElementById("calendar").innerHTML += calendarTable;
    }

    function go12() {
        for (i = 6; i < 12; i++) {
            calendar(i);  
       }
    }

    if (window.addEventListener) {
        window.addEventListener('load', go12, false);
    } else if (window.attachEvent) {
        window.attachEvent('onload', go12);
    }
})();

function redirect() {
    window.location.replace("./MyPage");
}

在我的剃刀页面中:

    public class MyPageyModel : PageModel
    {
        private readonly ILogger<MyPageModel> _logger;

        public PrivacyModel(ILogger<MyPageModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
           //somewhere in this class I need a DateTime variable that represents the day that the user clicked on the calendar
        }
    }
}

编辑 基于@Wowo Ot 的响应,我尝试了这样的方法来使用 OnPostMethod 将数据发送到我的班级:

function redirect() {
    $.ajax({
        type: 'POST',
        url: './MyPage', 
        dataType: 'string',

        data: { day: $("#DAY").val() },

        success: function (result) {
            return true;
        },
        error: function (ex) {
            return false;
        }
    });
}

在我的 Razor 页面中:

public string OnPostSetDate(int day)
{
    try
    {
         Debug.WriteLine(day);

          return "OK";
    }
    catch (Exception)
    {
         return "Error";
    }
}

但现在我收到一个错误:“加载资源失败:服务器响应状态为 500 () [https://localhost:44350/MyPage]”

标签: c#asp.net-core

解决方案


尝试这个

在你的控制器中

    [HttpPost]
    public string setDatePost(int day, int month, int year)
    {
        try
        {
            DateTime theDate = new DateTime(year, month, day);

            // your code to save Date

            return "OK";
        }
        catch (Exception)
        {
            return "Error";
        }

    }

在您的页面脚本中

<script type="text/javascript">
$(document).ready(function () {
    $("#CLK").click(function () {  // this is your button for selecting the day
        $.ajax({
            type: 'POST',
            url: '@Url.Action("setDatePost")', // the name of your action (function) in controller
            dataType: 'string',

            // these field represent your selection of day, month and year
            data: { day: $("#DAY").val(),month: $("#MONTH").val(), year: $("#YEAR").val() },

            success: function (result) {
            return true;
            },
            error: function (ex) {
                return false;
            }
        });
        return false;
    })
});

</script>

推荐阅读