Check if modelitem refers to currently logged in user with mvc identity I'm using MVC in order to generate a couple of views within my webpage. For a way of logging in, I've decided to use Asp.net's Identity, which I am very happy with.

However, I'm trying to find an efficient/ 'normal' way of testing if the user is logged in, and are looking at info that refers to them.

As a test, I found that:

 if (User.Identity.Name == (Html.DisplayFor(modelItem =&gt; item.Email).ToString()))
        {
            &lt;div&gt;THIS IS ME&lt;/div&gt;
        }


razor code works for this.

However, this seems quite inefficient, and I was wondering if there is a more appropriate way of telling 'is this their row in which they can edit'.
I would add the logic in the controller

 public ActionResult(){
    ApplicationDbContext db = new ApplicationDbContext();
    List&lt;ApplicationUser&gt; model = db.Users.ToList();

    // Viewbag just being an example for a model. It would be better to 
    // pass this into a property in the model that is being passed to the view. 
    foreach (var item in model)
    {
        ViewBag.UserEmail = System.Web.HttpContext.Current.User.Identity.Name 
                         == item.Email ? item.Email : null;
    }
  // If we were returning a viewmodel we could add this check into a
  // ApplicationUser ( public ApplicationUser AppUser {get; set;}) 
  // property which could then be accessed in the model as Model.AppUser. This 
  // would hold all the values for the application user. If that is           
  // something you would need 


 return View(model);
 }


This will assign the ViewBag.UserEmail to either the currently logged in users email or null. I added the full namespace because sometimes Current is not directly accessible

And in the view

 if(Viewbag.UserEmail != null)
 {
    &lt;div&gt; THIS IS ME&lt;/div&gt;
 }


This then just checks if the ViewBag is null and displays a code block if it is not.

This will still work in a loop. Because the ViewBag holds the current users email which can be checked against in a foreach

@foreach ( var item in Model){

       &lt;h4&gt;@item.Name&lt;/h4&gt;

       if(ViewBag.UserEmail == item.Email){
          &lt;button&gt;Edit &lt;/button&gt; // Should only be visible to logged in user 
       }

       // Or Like
        @( ViewBag.User == item.Email ? 
          Html.Raw("&lt;button class='btn btn-primary'&gt;Edit&lt;/button&gt;") :    
          Html.Raw("&lt;button class='btn btn-primary'&gt;View&lt;/button&gt;"))
}