Reputation: 493
I have a small MVC web application, where I want to use lists of objects - but only about 20 and without relations, so I dont want to setup DB. My idea is to create these lists on the run based on the data I have then pass them to Controller. So I created as a part of my model class "Hiker" this method which calls the constructor of the Hikers class
public List<Hikers> enterHikers()
{
List<Hikers> hikersList = new List<Hikers>
{
new Hikers("name1", "surname1", "email1"),
new Hikers("name2", "surname2", "email2")
};
return hikersList;
}
When it is called, it should return list of all entries I have. However, when I try to call it from the controller like this :
List<MVC.Models.Hikers> hikerlist = new Models.Hikers.enterHikers();
I get the error "MVC.Models.Hikers.enterHikers() is a 'method' but is used like a 'type'" . Does anybody know how to fix it and let me access my data from the controller? Thanks a lot.
Upvotes: 0
Views: 123
Reputation: 9606
A simple change to your code will fix the issue
List<MVC.Models.Hikers> hikerlist = (new Models.Hikers()).enterHikers();
How is it different from your code?
As the error clearly says, you can only use new
to create a type. Your code is trying to create an instance of a method, which is not what you want, then the method is not even accessible, because that is an instance method.
So, all you need to do is to create an instance of type Hikers
and invoke 'enterHikers` method of that instance.
Upvotes: 2
Reputation:
You'll have to make the function static
and use it a little different.
public static List<Hikers> enterHikers()
{
return new List<Hikers>
{
new Hikers("name1", "surname1", "email1"),
new Hikers("name2", "surname2", "email2")
}
}
and use it like:
List<MVC.Models.Hikers> hikerList = Models.Hikers.enterHikers();
Like Tetsuya said, this way you don't have to instantiate static methods, you can use them directly.
Upvotes: 1