I'm stuck on a problem trying to get a foreach block of code to work within an mvc controller and viewmodel.
What i'm trying to achieve is loop through the datetime values and if less than 60 seconds, show seconds. if more than 60 seconds but less than 1 hour show minutes. else show full datetime.
I can get the above to work, but it only displays the 1st record. I have tried putting foreach loops in various places but just cannot seem to get it to work.
Would appreciated a fresh pair off eyes to help with this.
public class MostRecentPostsViewModel
{
public List<MembersForumProperties> SelectMostRecentForumPosts { get; set; }
public string DateAndTimeOfForumPosts { get; set; }
}
public class IsPostLessThanOneHour
{
public static string DisplayPostInMinutesOrSeconds(string displyMostRecentForumPosts)
{
string displayTime = string.Empty;
//foreach (var postTime in mv.SelectMostRecentForumPosts)
//{
// dte = postTime.ForumMemberDateTimePostedPost;
//}
DateTime dtn = DateTime.Now;
DateTime timeOfPost = Convert.ToDateTime(displyMostRecentForumPosts);
TimeSpan ts = dtn - timeOfPost;
if (ts.TotalSeconds > 0 && ts.TotalSeconds < 60)
{
displayTime = "about " + ts.Seconds + " seconds ago";
}
else if (ts.TotalSeconds > 61 && ts.TotalSeconds < 3600)
{
displayTime = "about " + ts.Minutes + " minutes ago";
}
else
{
displayTime = displyMostRecentForumPosts;
}
return displayTime;
}
}
Controller
public PartialViewResult MostRecentMembersPosts()
{
var displyMostRecentForumPosts = _imf.DisplayMostRecentForumPosts().ToList();
var loopThroughDateTimes = displyMostRecentForumPosts.ToList();
var test = "";
foreach (MembersForumProperties t in loopThroughDateTimes)
{
test = t.ForumMemberDateTimePostedPost;
}
var membersMostRecentPost = new MostRecentPostsViewModel
{
SelectMostRecentForumPosts = displyMostRecentForumPosts,
DateAndTimeOfForumPosts = IsPostLessThanOneHour.DisplayPostInMinutesOrSeconds(test)
};
return PartialView("pvMostRecentMembersPost",membersMostRecentPost);
}
MAXand filtering by the author. Then run your logic on the return value to display the appropriate message.