我希望在這里計算它是我嘗試過的:
public int AgeCalc
{
get
{
DateTime now = DateTime.Today;
int agecalc = now.Year - DoB.Year;
if (DoB > now.AddYears(-Age))
Age--;
return Age;
}
}
但我收到此錯誤:
'-' 不能應用。
我的資料庫表中有一個名為Age. 我想要它做的是在DoB(出生日期)列中選擇日期時,它會計算人的年齡。
這是我的 T-SQL 代碼:
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
)
這是我在 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; }
}
}
uj5u.com熱心網友回復:
我已經檢查了你的代碼。但是,您可以通過以下更優雅高效的方式實作這一目標。
計算方法:
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;
}
模型:
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:剃刀視圖:
@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 class="table table-sm table-bordered table-striped">
<tr>
<th> <label asp-for="FirstName"></label></th>
<td> <input asp-for="FirstName" class="form-control" 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" class="form-control" 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" class="form-control">
<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" class="form-control" 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" class="form-control" readonly placeholder="Calculated age" /><span asp-validation-for="Age"></span></td>
</tr>
<tr>
<th> <button type="submit" class="btn btn-primary" 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>
}
控制器:加載視圖:
public IActionResult ViewCalculateAge()
{
return View();
}
控制器:API 計算年齡:
[HttpGet]
public ActionResult CalulateAgeFromDob(DateTime dateOfBirth)
{
var age = CalculateAge(dateOfBirth);
return Json(age);
}
注意:我CalculateAge在選擇DOB和呼叫APIfrom 后端時呼叫方法。
控制器:提交值并保存:
[HttpPost]
public IActionResult SubmitAge(CalculateStudentsAgeModel studentsAgeModel)
{
_context.calculateStudentsAgeModels.Add(studentsAgeModel);
_context.SaveChanges();
return RedirectToAction("ViewCalculateAge");
}
輸出:


轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511743.html
