Amy
Amy

Reputation: 71

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.

Upvotes: 5

Views: 955

Answers (2)

Huske
Huske

Reputation: 9296

Try this:

@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.Anon == true ? "Anonymous" : @post.Username)</p> 
            @post.Post_Desc
        </fieldset>
    </div>
}

EDIT: Sorry, the line should have said: @(post.Anon == true ? "Anonymous" : post.Post_Desc)

Upvotes: 0

Amadiere
Amadiere

Reputation: 11416

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.

Upvotes: 8

Related Questions