Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 C# - foreach

I am confused as to how to implement the following in my current foreach:

@foreach
(var post in Model."table".Where(w => w.Private_ID == 1).OrderBy(o => o.Date))
{
  <div class ="post">
    <fieldset>
      <p class="post_details">At @post.Post_Date By @post.Username</p>
      @post.Post_Desc
    </fieldset>
  </div>
}

so that post.Username will NOT show if @post.anon is TRUE (and so that it will say "Anonymous")

Thanks in advance for any advice/help/suggestions.

like image 493
Amy Avatar asked Aug 10 '11 09:08

Amy


1 Answers

You should be able to do something along the lines of:

@(post.anon ? "Anonymous" : post.Username)

Though I would consider doing most of this logic in the C#, rather than leaving it to the view (therefore, creating a specific view model with all of the logic already done. Meaning you can just loop through and not have to do any additional thinking:

@foreach(var post in Model.Posts)
{
   <div class ="post">
      <fieldset>
         <p class="post_details">At @post.Post_Date By @post.Poster</p>
         @post.Post_Desc
      </fieldset>
   </div>
}

Where @post.Poster in the above example is already preset with anonymous if it is required.

like image 183
Amadiere Avatar answered Sep 28 '22 03:09

Amadiere