1
\$\begingroup\$

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 => item.Email).ToString()))
 {
 <div>THIS IS ME</div>
 }

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'.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 31, 2015 at 11:18
\$\endgroup\$
1
  • \$\begingroup\$ Is this in a loop? What's item? \$\endgroup\$ Commented Apr 1, 2015 at 8:26

1 Answer 1

1
\$\begingroup\$

I would add the logic in the controller

 public ActionResult(){
 ApplicationDbContext db = new ApplicationDbContext();
 List<ApplicationUser> 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)
 {
 <div> THIS IS ME</div>
 }

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){
 <h4>@item.Name</h4>
 if(ViewBag.UserEmail == item.Email){
 <button>Edit </button> // Should only be visible to logged in user 
 }
 // Or Like
 @( ViewBag.User == item.Email ? 
 Html.Raw("<button class='btn btn-primary'>Edit</button>") : 
 Html.Raw("<button class='btn btn-primary'>View</button>"))
}
answered Apr 6, 2015 at 13:15
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.