5

我需要通过 MVC 控制器中的 jsonresult 将日期信息列表/json/array 动态传递给 Jquery UI Datepicker。

按照下面的链接,我可以在 datepicker 控件中突出显示选定的日期。 http://jquerybyexample.blogspot.com/2012/05/highlight-specific-dates-in-jquery-ui.html

    < script type ="text/javascript">
    $(document).ready( function () {

    var SelectedDates = {};
    SelectedDates[ new Date('05/28/2012' )] = new Date( '05/28/2012' );
    SelectedDates[ new Date('05/29/2012' )] = new Date( '05/29/2012' );
    SelectedDates[ new Date('05/30/2012' )] = new Date( '05/30/2012' );
    //want to replace the above three lines with code to get dates dynamically
    //from controller

    $( '#releasedate' ).datepicker({
        dateFormat: "mm/dd/yy" ,
        numberOfMonths: 3,
        duration: "fast" ,           
        minDate: new Date(),
        maxDate: "+90" ,
    beforeShowDay: function (date) {
        var Highlight = SelectedDates[date];
        if (Highlight) {
            return [true , "Highlighted", Highlight];
        }
        else {
            return [true , '', '' ];
        }
    }
});

上面的代码将突出显示日历控件(UIDatepicker)上的这三个特定日期。而不是像上面那样硬编码日期......我的挑战是从控制器动态获取这些日期并将其传递给上面 javascript 中的 var SelectedDates。

控制器json结果代码:

  public JsonResult GetReleasedDates(string Genre)
{

    var relDates = service.GetDates(Genre)//code to get the dates here

    return Json(relDates, JsonRequestBehavior .AllowGet);

    //relDates will have the dates needed to pass to the datepicker control.

}

谢谢您的帮助。

4

4 回答 4

11

第一种可能性是使用将直接序列化为 JSON 的模型:

public ActionResult Index()
{
    // TODO: obviously those will come from your service layer
    var selectedDates = new Dictionary<string, DateTime> 
    { 
        { new DateTime(2012, 5, 28).ToString("yyyy-M-dd"), new DateTime(2012, 5, 28) },
        { new DateTime(2012, 5, 29).ToString("yyyy-M-dd"), new DateTime(2012, 5, 29) },
        { new DateTime(2012, 5, 30).ToString("yyyy-M-dd"), new DateTime(2012, 5, 30) },
    };
    return View(selectedDates);
}

在视图中:

@model IDictionary<string, DateTime>

<script type ="text/javascript">
    $(document).ready(function () {

        var selectedDates = @Html.Raw(Json.Encode(Model));

        $('#releasedate').datepicker({
            dateFormat: "mm/dd/yy",
            numberOfMonths: 3,
            duration: "fast",
            minDate: new Date(),
            maxDate: "+90",
            beforeShowDay: function (date) {
                var key = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                var highlight = selectedDates[key];
                if (highlight) {
                    return [true, "Highlighted", highlight];
                }
                else {
                    return [true, '', ''];
                }
            }
        });
    });
</script>

另一种可能性是使用 AJAX 来检索selectedDates后者:

public ActionResult Index()
{
    return View();
}

public ActionResult GetSelectedDates()
{
    // TODO: obviously those will come from your service layer
    var selectedDates = new Dictionary<string, DateTime> 
    { 
        { new DateTime(2012, 5, 28).ToString("yyyy-M-dd"), new DateTime(2012, 5, 28) },
        { new DateTime(2012, 5, 29).ToString("yyyy-M-dd"), new DateTime(2012, 5, 29) },
        { new DateTime(2012, 5, 30).ToString("yyyy-M-dd"), new DateTime(2012, 5, 30) },
    };
    return Json(selectedDates, JsonRequestBehavior.AllowGet);
}

进而:

<script type ="text/javascript">
    $(document).ready(function () {
        $.getJSON('@Url.Action("GetSelectedDates")', function(selectedDates) {
            // Only inside the success callback of the AJAX request you have
            // the selected dates returned by the server, so it is only here
            // that you could wire up your date picker:
            $('#releasedate').datepicker({
                dateFormat: "mm/dd/yy",
                numberOfMonths: 3,
                duration: "fast",
                minDate: new Date(),
                maxDate: "+90",
                beforeShowDay: function (date) {
                    var key = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                    var highlight = selectedDates[key];
                    if (highlight) {
                        return [true, "Highlighted", highlight];
                    }
                    else {
                        return [true, '', ''];
                    }
                }
            });
        });
    });
</script>
于 2012-05-21T19:23:05.647 回答
2

有一个库可以将数据从控制器交换到 javascript,而无需进一步的 ajax 调用或内联 javascript。如果您需要每一页上的数据,您可以在过滤器中使用它。

http://jsm.codeplex.com

使用该库,您只需在 MVC 控制器操作中编写以下代码:

// Add the dates as objects to javascript - The object should only contain data
// which should be exposed to the public.
this.AddJavaScriptVariable("DatePickerController.Dates", service.GetDates(Genre));
// Execute the initialization function when the DOM has been loaded
// The function can be in a javascript file
this.AddJavaScriptFunction("DatePickerController.Ready");

您的 javascript 文件可能如下所示:

var DatePickerController = {
    Dates: null,
    Ready: function() {
        $("#releasedate").datepicker({
            dateFormat: "mm/dd/yy" ,
            numberOfMonths: 3,
            duration: "fast" ,           
            minDate: new Date(),
            maxDate: "+90" ,
            beforeShowDay: function (date) {
                var Highlight = DatePickerController.Dates[date];
                if (Highlight) {
                    return [true , "Highlighted", Highlight];
                }
                else {
                    return [true , '', '' ];
                }
            }
        });
    }
};

注意:您可能必须为使用 this.AddJavaScriptVariable 传递的日期创建一个特殊模型,该模型与日期选择器兼容。

于 2013-01-08T09:48:42.050 回答
1

进行ajax调用:

<script type ="text/javascript">
    $(document).ready( function () {

    var SelectedDates = {};
    //SelectedDates[ new Date('05/28/2012' )] = new Date( '05/28/2012' );
    //SelectedDates[ new Date('05/29/2012' )] = new Date( '05/29/2012' );
    //SelectedDates[ new Date('05/30/2012' )] = new Date( '05/30/2012' );

    $.ajax({
        url:'url'
        ,data:{}
        ,type:'get'
        ,success:function(data) {

        for(var i = 0, i < data.length; i++) {
            SelectedDates.push(new Date(data[i]));
        }

        $( '#releasedate' ).datepicker({
            dateFormat: "mm/dd/yy" ,
            numberOfMonths: 3,
            duration: "fast" ,           
            minDate: new Date(),
            maxDate: "+90" ,
            beforeShowDay: function (date) {
            var Highlight = SelectedDates[date];
                if (Highlight) {
                    return [true , "Highlighted", Highlight];
                }
                else {
                    return [true , '', '' ];
                }
            }
        });
    });
});
</script>
于 2012-05-21T19:16:50.597 回答
1

进行ajax调用以获取日期。ajax 请求成功后,使用结果配置数据选择器。

var configureDatePickers = function(dates){
    //setup datepicker in here...
};
$.get('url to get dates', {Genre: smoething}).success(configureDatePickers);

另一项建议。默认的 json 序列化程序不能很好地与 datetime 对象配合使用。因此我建议在序列化之前将日期作为字符串返回。例子:

var dates = Data.GetDates(genre).Select(x=>x.ToString("MM-dd-yyyy")).ToArray();
return Json(dates);
于 2012-05-21T19:17:43.223 回答