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'.
1 Answer 1
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>"))
}
item
? \$\endgroup\$