5

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.

1
  • 2
    it has a stupid name and I didn't want to embarrass myself :) Commented Aug 10, 2011 at 9:38

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't really like to put logic in the view, so I will take your advice, thank you so much!
0

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)

3 Comments

It's not working but I unserstand what it's trying to do. Thank you so much!
Why post.Anon == true ?, you can shorten that to: post.Anon ?
Yes you can. Just post.Anon would be enough. It's a personal choice. I like to put == true explicitly for readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.