1

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

1
  • 2
    what about making empAge a property Commented Sep 29, 2014 at 15:46

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

do not write business logic in view @ekad is right make property in view model

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.