开发者

ASP.Net MVC Razor View - Find Age with Date of Birth

I have a View that displays the Customer Details.

I would like to display age by the Date of Birth available.

I tried some thing like this.

@Html.DisplayTextFor(model => DateTime.Now.Date.Subtract(model.DOB))

where model.DOB has a value like 7/23/1985 12:00:00 AM

That gives me an error

Templates can be used only with 开发者_开发百科field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Can you please help me how i can display age with the Date of Birth i have.


First, figure out how to calculate an age: Calculate age in C#

Then add that code to your view model as a new property (or populate it when you're setting up your view model).

public int Age { get{
    DateTime now = DateTime.Today;
    int age = now.Year - DOB.Year;
    if (DOB > now.AddYears(-age)) age--;
    return age;
}}

Then use that property instead:

@Html.DisplayTextFor(model => model.AGE)


you can do like this

@{
var date=DateTime.Now.Date.Subtract(Model.DOB);

@Html.DisplayTextFor(model =>date.Years);
}


There are two issues here:

  1. This logic should be performed before you get to the view. Your view model should have an Age property on it, since that's what you really want to display. This property should be populated by the controller.
  2. Calculating someone's actual age can be tricky, since you probably don't want to literally show the person's age in terms of the number of 365-day years that they've been alive.

So you should start by modifying your model:

public class MyViewModel
{
    ...
    public TimeSpan Age {get;set;}
}

Then use the correct method to calculate someone's age when you're creating that model:

var model = new MyViewModel
            {
                ...
                Age = CalculateAge(person.DOB, DateTime.Now)
            };

Then modify your View code:

@Html.DisplayTextFor(model => model.Age)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜