0

目前,我的 page.html 如下,它大部分都在工作,但我有一些奇怪的地方,我的日期显示如下:

2013-05-24T13:09:40.927 2013-05-24T13:09:40.927 10>  
 •2013-05-24T13:11:32.823 2013-05-24T13:11:32.823 100>  
 •2013-05-24T13:12:22.653 2013-05-24T13:12:22.653 10>  
 •2012-12-12T00:00:00 2012-12-12T00:00:00 10>  

日期解析它们会很好,但不知道该怎么做,我也想要2个输入字段:

<input type="date" class="ui-corner-all" data-bind="value: newPeriodFrom" />
               <input type="date" class="ui-corner-all" data-bind="value: newPeriodTo" />

成为日期选择器甚至更好的屏蔽日期字段,这怎么可能?

page.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
        <body>`enter code here`
        <script src="Core/Scripts/jquery-2.0.0.js"></script>
         <script src="Core/Scripts/jquery-ui-1.10.0.js"></script>
          <script src="Scripts/jquery.signalR-1.1.1.min.js"></script>
           <script src="signalr/hubs"></script>
            <script src="Scripts/knockout-2.2.1.js"></script>   
            <script src="/Core/Scripts/modernizr-2.6.2.js" type="text/javascript"></script>
            <link href="GUI/themes/base/jquery-ui.css" rel="stylesheet" />
            <link href="GUI/themes/base/jquery-ui.css" rel="stylesheet" />
            <script src="Core/Scripts/jquery.maskedinput-1.2.2.js"></script>
            <!-- when this page is loaded into the dom, the inner html of this div will be re-written to `be the session id, feels hacky but works -->
            <div id="sessionIdDiv">174f869f-cf27-4dd4-a031-d518fa5eb9cc</div>
    <!-- ReSharper disable StatementIsNotTerminated -->
            <script>
                $(function () {

                    //call this func to open a connection before calling  hub methods ie window.hubReady.done(function....



                   // $(function () {
                   //     window.hubReady = $.connection.periodTransactionComs.start();
                  ////  });

                    //returns the context session ID 
                    function sessionId() {                   
                        var licenceGuid = $('#sessionIdDiv').text();
                        return licenceGuid;
                    }

                    //poll the server for updates, gives us "realtime", 
                    //ie any updates directly to SQL or anywhere else will be 
                    //dragged in, helps prevent dirty data  my old cache engine caused.
             ///      $(function() {
               //     window.setInterval(function() {
             //           this.hub = $.connection.periodTransactionComs;
                  //      this.hub.server.getAll(sessionId());
    //
               //     }, 1000);



                    //the main KO view model 
                    function periodViewModel(periodId, validFrom, validTo, number, ownerViewModel) {
                        this.pId = periodId;
                        this.validFrom = ko.observable(validFrom);
                        this.validTo = ko.observable(validTo);
                        this.number = ko.observable(number);
                        this.remove = function () { ownerViewModel.removePeriod(this.pId) }
                        this.notification = function (b) { notify = b }


                        this.validFrom.subscribe(function (newValue) {
                            ownerViewModel.updatePeriod(ko.toJS(self));
                        });

                        this.validTo.subscribe(function (newValue) {
                            ownerViewModel.updatePeriod(ko.toJS(self));
                        });

                        this.number.subscribe(function (newValue) {
                            ownerViewModel.updatePeriod(ko.toJS(self));
                        });


                    }


                    //Task List View Model
                    function periodListViewModel() {
                        //Handlers for our Hub callbacks

                        this.hub = $.connection.periodTransactionComs;
                        this.periods = ko.observableArray([]);
                        this.newPeriodFrom = ko.observable();
                        this.newPeriodTo = ko.observable();
                        this.newPeriodNumber = ko.observable();
                       var periods = this.periods;
                        var self = this;
                        var notify = true;
                      this.newPeriodFrom();
                      this.newPeriodTo();
                      this.newPeriodNumber("1");

                        //Initializes the view model
                        this.init = function () {

                            this.hub.server.getAll(sessionId());

                        }

                        //map the JSON to a KO model
                     this.hub.client.periodAll = function (allPeriods) {
                         var mappedPeriods = $.map(allPeriods, function (item) {
                             alert("Mapping id:" + item.Id + " number " + item.number + " Number:" + item.Number + " From: " + item.ValidFrom + " to: " + item.ValidTo);
                                return new periodViewModel(item.Id, item.ValidFrom, item.ValidTo,
                                         item.Number, self)
                            });
                         periods(mappedPeriods);
                     }



                        //server dynamicly calls this method when a row is updated in this context
                        //only returns to caller connected.
                        this.hub.client.periodUpdated = function (t) {
                            var period = ko.utils.arrayFilter(periods(),
                                         function (value)
                                         { return value.pId == t.Id; })[0];
                            notify = false;
                            period.validFrom(t.ValidFrom);
                            period.validTo(t.ValidTo);
                            period.number(t.Number);
                            alert("periodupdated:  " + t.ValidFrom + " " + t.validTo + "  " + t.Number);
                            notify = true;
                        };

                        //all serverside errors will dynamicly calll this to report errors.
                        this.hub.client.reportError = function (error) {
                            $("#error").text(error);
                            $("#error").fadeIn(1000, function () {
                                $("#error").fadeOut(3000);
                                alert(error);
                            });
                        }
                        //dynamicly called add method updates clientside viewmodel.
                        this.hub.client.periodAdded = function (t) {

                            periods.push(new periodViewModel(t.Id, t.ValidFrom, t.ValidTo, t.Number, self));
                            alert("Period Added Id:" + t.Id + " number " + t.number + " Number:" + t.Number + " From: " + t.ValidFrom + " to: " + t.ValidTo);
                        };
                        //dynamicly called add method updates clientside viewmodel.
                        this.hub.client.periodRemoved = function (periodId) {
                            var period = ko.utils.arrayFilter(periods(), function (value) { return value.pId == periodId; })[0];
                            periods.remove(period);
                        };
                        //View Model 'Commands'

                        //To create a task
                        this.addPeriod = function () {
                            var t = { "validFrom": this.newPeriodFrom(), "validTo": this.newPeriodTo(), "number": this.newPeriodNumber() };
                            alert("values of add  " + this.newPeriodFrom() + this.newPeriodTo() + this.newPeriodNumber());
                            this.hub.server.add(t,sessionId()).done(function () {
                                alert('added')
                            }).fail(function (e) {
                                alert(e);
                            });
                            this.newPeriodFrom("");
                          this.newPeriodTo("");
                           this.newPeriodNumber("0");
                        }

                        //To remove a task client side only
                        this.removePeriod = function (periodId) {
                            this.hub.server.remove(periodId);
                        }

                        //To update this task client side only
                        this.updatePeriod = function (period) {
                            if (notify)
                                alert('notify');
                                this.hub.server.update(period);
                        }


                    }

                    var vm = new periodListViewModel();
                    ko.applyBindings(vm);
                    // Start the connection
                    $.connection.hub.start().done(function () { vm.init(); });

                    ko.bindingHandlers.masked = {
                        init: function (element, valueAccessor, allBindingsAccessor) {
                            var mask = allBindingsAccessor().mask || {};
                            $(element).mask(mask);
                            ko.utils.registerEventHandler(element, 'focusout', function () {
                                var observable = valueAccessor();
                                observable($(element).val());
                            });
                        },
                        update: function (element, valueAccessor) {
                            var value = ko.utils.unwrapObservable(valueAccessor());
                            $(element).val(value);
                        }
                    };







                });



            </script>
    <!-- ReSharper restore StatementIsNotTerminated -->

            <h2> Add period</h2>
            <form data-bind="submit: addPeriod">
               <input type="date" class="ui-corner-all" data-bind="value: newPeriodFrom" />
               <input type="date" class="ui-corner-all" data-bind="value: newPeriodTo" />
                <input type ="number" class="ui-corner-all" data-bind="value: newPeriodNumber, valueUpdate: 'afterkeydown'" placeholder="Number of period transactions?" />
               <input class="ui-button" type="submit" value="Add" />
            </form>

            <h2>Our periods</h2>


           <ul data-bind="template: { name: 'periodTemplate', foreach: periods }, visible: periods().length > 0">
            </ul>

            <script type="text/html" id="periodTemplate">
                <!--Data Template-->
                <li>

                   <span data-bind="text: validFrom"></span>
                   <span data-bind="text: validTo"></span>
                   <span data-bind="text: number"></span>>
                    <input class="ui-button" type="button" href="#" data-bind="click: remove" value="x"/>

                </li>
            </script>
            <div id="error" class="validation-summary-errors"></div>

        </body>

    </html>

和我的枢纽

using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    using ProactisSupportPortal;



    namespace Core
    {
        [HubName("periodTransactionComs")]
        public class PeriodTransactionHub : Hub
        {
            public bool Add(LicencePeriodTransaction licencePeriodTransaction, string sessionId)
            {
                try
                {
                    using (var databaseContext = new LGenEntities())
                    {

                        //find the licence where 2session/licence guid 
                        Licence oLicence = databaseContext.Licences.FirstOrDefault(l=>l.session == sessionId); //;

                        if (oLicence != null)
                        {



                            //now add the new licence period transaction

                            var lpt = new LicencePeriodTransaction
                                {
                                    Number = licencePeriodTransaction.Number,
                                    ValidFrom = licencePeriodTransaction.ValidFrom,
                                    ValidTo = licencePeriodTransaction.ValidTo,
                                    LicenceID = oLicence.LicenceId,
                                    Licence = oLicence
                                };

                            databaseContext.LicencePeriodTransactions.Add(lpt);
                           databaseContext.Entry(oLicence).State = EntityState.Unchanged;


                            //commit
                            databaseContext.SaveChanges();
                            //notify connected client
                            Clients.Caller.periodAdded(lpt);

                            return true;
                        }
                        return
                            Clients.Caller.reportError(
                                "Null reference in:  public bool AddPeriodTransaction(LicencePeriodTransaction licencePeriodTransaction, string sessionId) ");


                    }
                }
                catch
                    (Exception ex)
                {
                    Clients.Caller.reportError(ex);
                    return false;
                }
            }

            //update
            public bool Update(LicencePeriodTransaction updatedPeriod)
            {
                try
                {
                    using (var databaseContext = new LGenEntities())
                    {
                        var oldTask =
                            databaseContext.LicencePeriodTransactions.FirstOrDefault(p => p.Id == updatedPeriod.Id);
                        if (oldTask != null)
                        {
                            oldTask.Number = updatedPeriod.Number;
                            oldTask.ValidTo = updatedPeriod.ValidTo;
                            oldTask.ValidFrom = updatedPeriod.ValidFrom;
                            databaseContext.SaveChanges();
                            Clients.Caller.periodUpdated(oldTask);
                            return true;
                        }
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Clients.Caller.reportError(ex);
                    return false;
                }
            }

            //Remove
            public bool Remove(int licencePeriodTransactionId)
            {
                try
                {
                    using (var databaseContext = new LGenEntities())
                    {
                        var licencePeriod =
                            databaseContext.LicencePeriodTransactions.FirstOrDefault(p => p.Id == licencePeriodTransactionId);
                        databaseContext.LicencePeriodTransactions.Remove(licencePeriod);
                        databaseContext.SaveChanges();
                        Clients.Caller.periodRemoved(licencePeriodTransactionId);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Clients.Caller.reportError(ex);
                    return false;
                }
            }

            //get all for licence by session.
            public void GetAll(string sessionId)
            {
                try
                {
                    using (var databaseContext = new LGenEntities())
                    {

                        var res = databaseContext.LicencePeriodTransactions.Where(p => p.Licence.session == sessionId).ToArray();
                        Clients.Caller.periodAll(res);
                    }
                }
                catch (Exception ex)
                {
                    Clients.Caller.reportError(ex);
                }
            }
        }
    }
4

2 回答 2

0

您可以在敲除中使用自定义绑定来格式化您的日期字符串和日期值,因为它们进入和离开您的视图模型。

在 javascript 中处理日期时,我喜欢使用 jQuery 和moment.js库,所以我将日期显示为字符串的自定义绑定如下所示:

ko.bindingHandlers.dateString = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
      var value = valueAccessor(),
        allBindings = allBindingsAccessor();
      var valueUnwrapped = ko.utils.unwrapObservable(value);
      if (valueUnwrapped) {
        var pattern = 'MM/DD/YYYY';
        $(element).text(moment(valueUnwrapped).format(pattern));
      }
    }
  }

并像这样应用:

<span data-bind="dateString: dateData"></span>

对于处理值,我使用如下所示的 dateValue 自定义绑定:

 ko.bindingHandlers.dateValue = {
    init: function (element, valueAccessor) {
      $(element).change(function () {
        var value = $(element).val();
        if (moment(value).isValid()) {
          valueAccessor()(moment(value).toDate());
        }
      });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
      var value = valueAccessor(),
        allBindings = allBindingsAccessor();
      var valueUnwrapped = ko.utils.unwrapObservable(value);
      if (valueUnwrapped) {
        var pattern = 'MM/DD/YYYY';
        $(element).val(moment(valueUnwrapped).format(pattern));
      }
    }
  }

并像这样应用:

<input type="text" data-bind="dateValue: dateData" />
于 2013-05-25T00:20:27.540 回答
0

您可以在客户端或服务器端将日期格式化为首选格式:

  1. 服务器端,只需将属性设为字符串,然后以所需格式在您的日期调用 ToString。

  2. 客户端,您可能有计算属性,将格式化日期和数据绑定到该属性。

样本:

model.formatedDate = ko.computed(function() {
    return formatDateFunction(model.startDate);
});

检查示例http://blog.stevenlevithan.com/archives/date-time-format以了解 JavaScript 中的日期格式逻辑。

于 2013-05-24T18:59:55.147 回答