将值从MVC控制器传递到javascript代码

时间:2012-05-21 19:04:52

标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-3

我需要通过MVC控制器中的jsonresult动态地将list / json /日期数组信息传递给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)上的特定三个日期。而不是上面的硬编码日期...我的挑战是从控制器动态获取这些日期并将其传递给var的SelectedDates in上面的javascript。

控制器jsonresult代码:

  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 个答案:

答案 0 :(得分:9)

第一种可能性是使用将直接序列化为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>

答案 1 :(得分:2)

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

http://jsm.codeplex.com

使用该库,您只需在MVC Controller Action中编写以下代码:

// 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传递的日期创建一个特殊模型,该模型与datepicker兼容。

答案 2 :(得分: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>

答案 3 :(得分: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);