【问题标题】:Kendo UI DatePicker Javascript and HttpContext.Session C#, MVCKendo UI DatePicker Javascript 和 HttpContext.Session C#, MVC
【发布时间】:2016-09-14 17:14:21
【问题描述】:

我们正在使用 Kendo UI 日期选择器(Javascript 版本),我想在其中填充一个 HttpContext.Session 变量,该变量具有从我们的 KendoUI 日期选择器传递并传递给我们的控制器的日期,Session 在控制器中设置。

KendoUI DatePicker 用于多个模板中的多个页面。 如果设置了变量,我的目标是让在 Session 中选择和设置的日期被传递回 KendoUI DatePicker。如果未设置所选日期,我希望将日期选择器的值设置为今天或 new Date()。

我的 Javascript:

  <script>
   $(document).ready(function () {

    var SelectedDate = new Date();
 //Is this even correct?
    if('@HttpContext.Current.Session["CalendarSelectedDate"]' != '@DateTime.Now'){
        SelectedDate == '@HttpContext.Current.Session["CalendarSelectedDate"]';
        console.log("In if");
    }else{
        SelectedDate == new Date();
        console.log("In else");
    }
    console.log('Selected date: ' + SelectedDate);

   // WANT TO SET VALUE FROM SESSION DATE HERE!!!
    $("#datepicker").kendoDatePicker({
        value: SelectedDate,
        min: new Date(),
        format: "MM/dd/yyyy",
        change: function () {
            var value = this.value();
            console.log(value); //value is the selected date in the datepicker
            initialGetEventTypes();
        }
    });
    initialGetEventTypes();
});
  </script>

  //The AJAX call to the controller
  <script type="text/javascript">

function initialGetEventTypes() {
     @{ 
         var dateFromHub = DateTime.Now;
         var obj = HttpContext.Current.Session["CalendarSelectedDate"];
         if(obj != null)
         {
             dateFromHub = Convert.ToDateTime(obj);
         }
     }

    console.log('Session Selected Date: @dateFromHub.ToShortDateString()');
    $('#categoryLoading').show();
    var startDateTime = $("#datepicker").val();
    var endDateTime = startDateTime;
    var url = '@Url.Action("GetTotalEventTypeIdsByDate", "MuseumUniversalCalendar")';

        $.ajax({
            url: url,
            type: "GET",
            cache: false,
            dataType: "json",
            data: { startDateTime: startDateTime, endDateTime: endDateTime },
            success: function (data) {
                $('#categoryLoading').hide();
                $('.product-item').find('.categoryAvaiableCapacity').html("Not Available");
                var list = JSON.stringify(data);
                $("#eventTypeName").find('option').remove().end();
                $.each(data.result, function (i, eventTypes) {
                        $('.product-item').each(function () {
                            if ($(this).attr('data-galaxyeventnamefromnop') == eventTypes.EventName) {
                                $(this).find('.categoryAvaiableCapacity').html(eventTypes.Available + ' Available');
                           }
                        });
                    });

                if (data.result.length === 0)  {
     $("#noEvents").text('@T("museum.noeventavailablemessage")');

                }else{
                    // console.log("we are here")
                    $("#noEvents").text("");
                }

            },
            error: function(xhr, error, data) {
                console.log(xhr, error, data);
                $('#categoryLoading').hide();
                $("#eventTypeName").find('option').remove().end();
                alert("An error occurred getting the Event Types");
            }
        });
   }

</script>

我的控制器方法:

  public class MuseumUniversalCalendarController : Controller
{
    //[NonAction]
     public JsonResult GetTotalEventTypeIdsByDate(MuseumUniversalCalendarModel model, DateTime startDateTime, DateTime endDateTime)
    {
        //Set selected Date for session
        HttpContext.Session["CalendarSelectedDate"] = startDateTime;

        var result = eventListOfEvents(model, startDateTime, endDateTime);
        return Json(new { result }, JsonRequestBehavior.AllowGet);
    }


    public List<cEvent> eventListOfEvents(MuseumUniversalCalendarModel model, DateTime startDateTime, DateTime endDateTime)
    {
        var eventTypeIdList = ExternalDataAccess.HubServiceCalls.GetAvailableEventsByEventDate(startDateTime, endDateTime);

        foreach(var eventTypeItem in eventTypeIdList)
        {
            model.AvailableGalaxyEventTypes.Add(new SelectListItem
            {
                Text = eventTypeItem.EventName,
                Value = eventTypeItem.EventTypeId.ToString()
            });
        }

        var fullOutEventlist = eventTypeIdList;
        var totalsList = eventTypeIdList.GroupBy(e => e.EventName.ToString()).Select(grp => grp.First()).ToList();
        totalsList.ForEach(x => x.Available = eventTypeIdList.Where(y => y.EventName == x.EventName).Select(z => z.Available).Sum());
        return totalsList;
    }

【问题讨论】:

标签: c# jquery asp.net-mvc kendo-ui datepicker


【解决方案1】:

我会将数据选择器包装在一个局部视图中,该视图可以使用剃刀将会话值读取到视图的 JS 中。你甚至可以将它隔离到它自己的控制器中。

Views/Shared/_DatePickPartial.cshtml

<div id='datepicker'></div>
<script>
    $("#datepicker").kendoDatePicker({
    value: '@HttpContext.Session["CalendarSelectedDate" ] ?? new Date()',
    min: new Date(),
    format: "MM/dd/yyyy",
    change: function () {
         //send ajax to partial action DatePickPartialUpdate which will add value to session
    }
});
</script>

SomeController _DatePickPartial

public ActionResult _DatePickPartialUpdate(DateTime2 value)
{
    Session["CalendarSelectedDate"] = value;
}

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多