Reputation: 4791
Is there any way to check which View invoked method in ASP.NET MVC?
For example, I have simple static method that returns posts form database and I have two views that are doing similar thing, but still not the same. On one view I'm listing post from logged in user, and on the other I'm showing posts from all users (imagine that like Facebook pages where on the wall you only see your posts, and on the NewsFeed page you can see both your's and your friends posts).
So my concrete question would be, can I implement my method to do something like this:
public static List<Post> GetPosts(int BlockNumber, int BlockSize, string id)
{
ApplicationDbContext db = new ApplicationDbContext();
int startIndex = (BlockNumber - 1) * BlockSize;
var listPosts = db.Posts.ToList();
if (METHOD INVOKED FROM ProfilePage SHOW ONLY CURRENT USER POSTS)
{
listPosts = listPosts.Where(p => p.UserId == id).Reverse().ToList();
}
else if(METHOD INVOKED FROM NEWSFEED SHOW ALL USERS POSTS)
{
listPosts = listPosts.Reverse().ToList();
}
var posts = listPosts.Skip(startIndex).Take(BlockSize).ToList();
return posts;
}
My idea is to simple send empty string for id from NewsFeedController, and then check if id is empty show all posts, and if id value is present and not empty show only posts for user with that id. I believe that would work, but I'm interested is there any other, nicer way to do it. Can ASP.NET MVC and C# do something like this? This two views are doing similar things and I would like to avoid unnecessary redundancy of code.
Upvotes: 0
Views: 1288
Reputation: 203
You can pass UserId as nullable int and call it in explicit way from your controller. I mean something like that:
public static List<Post> GetPosts(int BlockNumber, int BlockSize, string id, int? userId)
This way you get clean and readable interface, without any 'magic' in the GetPosts method.
If you are sure that you want to follow the idea of "known caller" you can read more on this topic here: How can I find the method that called the current method? however this would be nightmare in further work with this code. Also - have you tought how to test such call?
Upvotes: 1