【问题标题】:Age not working as expected when selecting from jquery date picker and tabbing off dob field从 jquery 日期选择器中选择并关闭 dob 字段时,年龄未按预期工作
【发布时间】:2020-08-13 00:06:34
【问题描述】:

我正在尝试使用日期选择器从我的模型中计算年龄,我还必须考虑用户的选项卡,但它也不起作用。

<div class="card-body">
    @Html.LabelFor(m => m.DOB)
    <input asp-for="DOB" class="form-control" />
    <span asp-validation-for="DOB" class="text-danger"></span>
</div>                                       

<div class="form-group">
    @Html.LabelFor(m => m.Age)
    <input asp-for="Age" class="form-control" />

    <span asp-validation-for="Age" class="text-danger"></span>
</div>

在我的模型中

[Required(ErrorMessage = " Date of Brith is Required")]
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DOB { get; set; }
public int Age {
       get {
            DateTime now = DateTime.Today;
            int age = now.Year - GetAge(DOB);
            if (age == 0) return 0;
            if (DOB > now.AddYears(-age)) age--;
            return age;
        }
    }

    public static int GetAge(DateTime birthDate) {
        DateTime n = DateTime.Now; // To avoid a race condition around midnight
        int age = n.Year - birthDate.Year;
        if (age == 0) return 0;
            
        if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
            age--;

        return age;
   }

但是当我查看页面时,即使选择了日期,它也只会输出零。我正在使用 jQuery JavaScript 库 v3.3.1

【问题讨论】:

    标签: c# jquery asp.net-core


    【解决方案1】:

    我正在尝试使用日期选择器从我的模型中计算年龄,我还必须考虑用户的选项卡,但它也不起作用。

    您需要知道getter访问器是通过在服务器端创建实例来调用的。您所做的只是客户端操作,因此无法正常工作。

    根据您的要求,您可以使用 jQuery 来调用该方法:

    型号:

    public class TestModel
    {
        [Required(ErrorMessage = " Date of Brith is Required")]
        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime DOB { get; set; }
        public int Age
        {
            get
            {
                DateTime now = DateTime.Today;
                int age = GetAge(DOB);     //change this...
                if (age == 0) return 0;
                if (DOB > now.AddYears(-age)) age--;
                return age;
            }
        }
    
        public static int GetAge(DateTime birthDate)
        {
            DateTime n = DateTime.Now; 
            int age = n.Year - birthDate.Year;
            if (age == 0) return 0;
    
            if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
                age--;
    
            return age;
        }
    }
    

    查看(Home/Index.cshtml):

    @model TestModel
    <div class="card-body">
        @Html.LabelFor(m => m.DOB)
        <input asp-for="DOB" class="form-control" />
        <span asp-validation-for="DOB" class="text-danger"></span>
    </div>
    
    <div class="form-group">
        @Html.LabelFor(m => m.Age)
        <input asp-for="Age" class="form-control" />
    
        <span asp-validation-for="Age" class="text-danger"></span>
    </div>
    @section Scripts
    {
    <script>
        $("#DOB").change(function () {
            var date = this.value;
            window.location.href = "/Home/Index?date=" + date;
        });
    </script>
    }
    

    控制器:

    public class HomeController : Controller
    {
        public IActionResult Index(string date)
        {
            if (date != null)
            {
                var model = new TestModel()
                {
                    DOB = DateTime.Parse(date)
                };
                return View(model);
            }
            return View();
        }
    }
    

    结果(缺点是会改变请求的url):

    第二种方式,如果不想更改请求url:

    查看:

    <script>
        $("#DOB").change(function () {
            var date = this.value;
            $.ajax({
                url: 'Home/Index?date=' + date,
                type: 'Get',
                success: function (data) {
                    $('#Age').val(data);
                }
            })
        });
    </script>
    

    控制器:

    public IActionResult Index(string date)
    {
        if (date != null)
        {
            var model = new TestModel()
            {
                DOB = DateTime.Parse(date)
            };
            return Ok(model.Age);
        }
        return View();
    }
    

    另一种方式是完全使用jQuery来计算年龄,而不是调用服务器端代码:

    <script>
        $("#DOB").change(function () {           
            var dob = this.value;
            dob = new Date(dob);
            var today = new Date();
            var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
            $('#Age').val(age);
        });
    </script>
    

    或者:

    <script>
        $("#DOB").change(function () {
            var now = new Date();
            var age = GetAge($("#DOB").val());
            if (age == 0) return 0;
            $("#Age").val(age);
        });
        function GetAge(birthDate) {
            var n = new Date()// To avoid a race condition around midnight
            var birth = new Date(birthDate)
            var age = n.getFullYear() - birth.getFullYear();
            if (age == 0) {
                return 0;
            }
            if (n.getMonth() < birth.getMonth() || (n.getMonth() == birth.getMonth() && n.getDay() < birth.getDay())) {
                age--;
            }
            return age;
        }
    </script>
    

    型号:

    public class TestModel
    {
        [Required(ErrorMessage = " Date of Brith is Required")]
        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime DOB { get; set; }
        public int Age { get; set; }
    }
    

    【讨论】:

    • 一如既往的精彩回答
    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多