Home > OS >  Get age to calculate from birthday in T-SQL and ASP.NET Core MVC
Get age to calculate from birthday in T-SQL and ASP.NET Core MVC

Time:10-08

I would like it to be calculated here is what I have tried:

public int AgeCalc
{
    get
    {
        DateTime now = DateTime.Today;
        int agecalc = now.Year - DoB.Year;

        if (DoB > now.AddYears(-Age)) 
             Age--;

        return Age;
    }
}

but I get this error:

'-' cannot be applied.

I have a column in my database table called Age. What I want it to do is when a date is selected in the DoB (Date of Birth) column, it calculates the age of the person.

This is my T-SQL code:

CREATE TABLE [dbo].[Students]
(
    [StudentId] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    [FirstName] nvarchar(200) NOT NULL,
    [LastName] nvarchar(400) NOT NULL,
    [DoB] datetime NULL,
    [Age] int NOT NULL,
    [Gender] char(10) NULL CHECK (Gender = 'Male' OR Gender = 'Female' OR Gender = 'Other'),
    [ParentOrGuardian] nvarchar(400),
    [PaymentEmail] varchar(255) NOT NULL,
    [ContactNumber] char(10) NULL
)

This is my model class in C#:

namespace MusicDataApplication.Models
{
    using Microsoft.Ajax.Utilities;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;

    public partial class Student
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Student()
        {
            this.Lessons = new HashSet<Lesson>();
        }
    
        public int StudentId { get; set; }

        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name = "Birthday")]
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> DoB { get; set; }

        public int Age { get; set; }
        public string Gender { get; set; }

        [Display(Name = "Parent/ Guardian")]
        public string ParentOrGuardian { get; set; }
        [Display(Name = "Payement Email")]
        [DataType(DataType.EmailAddress)]
        public string PaymentEmail { get; set; }
        [Display(Name = "Contact Number")]
        public string ContactNumber { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Lesson> Lessons { get; set; }
    }
}

CodePudding user response:

I have checked your code. However, you could achieve that in following way which is more elegant efficient.

Calculate Method:

public object CalculateAge(DateTime dateOfBirth)
        {
            //DateTime birth = new DateTime(1990, 08, 02);
            DateTime birth = dateOfBirth;
            DateTime today = DateTime.Now;
            TimeSpan span = today - birth;
            DateTime age = DateTime.MinValue   span;

            // Make adjustment due to MinValue equalling 1/1/1int years = age.Year - 1;
            int months = age.Month - 1;
            int days = age.Day - 1;

            // You even can Print out not only how many years old they are but give months and days as well
            var ageInYMD = string.Format("{0} years, {1} months, {2} days", age.Year, months, days);
            var ageInY = string.Format("{0} years", age.Year);

            return age.Year;
        }

Model:

public class CalculateStudentsAgeModel
    {
        [Key]
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DoB { get; set; }
        public int Age { get; set; }
       
        public string Gender { get; set; }
       
    }

HTML: Razor View:

@model MVCApps.Models.CalculateStudentsAgeModel
<div>
    <form asp-action="SubmitAge" method="post" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="StudentId" />
        <div>
            <h4><strong>Student Details</strong> </h4>

            <table >

                <tr>
                    <th> <label asp-for="FirstName"></label></th>
                    <td> <input asp-for="FirstName"  placeholder="Enter first name" /><span asp-validation-for="FirstName"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="LastName"></label></th>
                    <td> <input asp-for="LastName"  placeholder="Enter last name" /><span asp-validation-for="LastName"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Gender"></label></th>

                    <td>
                        <select asp-for="Gender" >
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                        <span asp-validation-for="Gender"></span>

                    </td>
                </tr>
                <tr>
                    <th> <label asp-for="DoB"></label></th>
                    <td> <input asp-for="DoB" id="dateOfBirth"  placeholder="Enter date of birth" /><span asp-validation-for="DoB"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Age"></label></th>
                    <td> <input asp-for="Age" id="Age"   readonly placeholder="Calculated age" /><span asp-validation-for="Age"></span></td>
                </tr>

                <tr>
                    <th>  <button type="submit"  style="width:107px">Save Info</button></th>
                    <td> </td>
                </tr>
                <tr>
                    <th>@Html.ActionLink("Back To List", "MemberList", new { /* id=item.PrimaryKey */ }, new { @class = "btn btn-success" })</th>
                    <td> </td>
                </tr>
            </table>
        </div>
    </form>

</div>

@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {

         
            $('#dateOfBirth').change(function () {
               
                var dateOfBirth = $('#dateOfBirth').val();

                console.log(dateOfBirth);
                $.ajax({
                    url: '/Userlog/CalulateAgeFromDob',
                    type: 'GET',
                    dataType: 'json',
                    data: { dateOfBirth: dateOfBirth },
                    success: function (response) {
                        console.log(response);
                        $("#Age").val(response);
                    },
                    error: function () {
                        alert('Error!');
                    }
                });
            });

        });
    </script>
}

Controller:Load View:

public IActionResult ViewCalculateAge()
        {
            return View();
        }

Controller:API Calculate Age:

        [HttpGet]
        public ActionResult CalulateAgeFromDob(DateTime dateOfBirth)
        {
            var age = CalculateAge(dateOfBirth);
            return Json(age);
        }

Note: I am calling CalculateAge method while selecting the DOB and calling the API from backend.

Controller:Submit Value and Save :

        [HttpPost]
        public IActionResult SubmitAge(CalculateStudentsAgeModel studentsAgeModel)
        {
            _context.calculateStudentsAgeModels.Add(studentsAgeModel);
            _context.SaveChanges();

            return RedirectToAction("ViewCalculateAge");
        }

Output:

enter image description here

enter image description here

  • Related