Reputation: 107
Visual Studio 2012 MVC4
Hi,
I am currently working on the following class for employee which contains a method for determining the employee's age:
public class Employee
{
public string firstName { get; set; }
public string lastName { get; set; }
public string empID { get; set; }
public bool isManager { get; set; }
public string empTel { get; set; }
public string empEml { get; set; }
public string empDOB { get; set; }
public string empBio { get; set; }
public int empAge()
{
DateTime birthdate = DateTime.Parse(empDOB);
int age = DateTime.Now.Year - birthdate.Year;
if (DateTime.Now.DayOfYear < birthdate.DayOfYear)
{
age = age - 1;
}
return age;
}
public string empMarketLocation { get; set; }
public double WeeklyHours { get; set; }
public Employee()
{
}
}
}
I initially thought I would be able to display the result of the method in my view withe the following line:
@Html.DisplayFor(ModelItem => Model.empAge())
However, I get the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
I am uncertain if I cannot use HTML Display or if I simply have written it wrong. Any thoughts?
Thanks
Upvotes: 1
Views: 1880
Reputation: 14624
You can use empAge
with Html.DisplayFor
helper method if it's a property instead of a method. Change empAge
to a property
public int empAge
{
get
{
DateTime birthdate = DateTime.Parse(empDOB);
int age = DateTime.Now.Year - birthdate.Year;
if (DateTime.Now.DayOfYear < birthdate.DayOfYear)
{
age = age - 1;
}
return age;
}
}
and change this
@Html.DisplayFor(ModelItem => Model.empAge())
to this
@Html.DisplayFor(m => m.empAge)
Upvotes: 2