Thanh Tran
Thanh Tran

Reputation: 117

ASP.NET MVC View - Display something base on Authorize

Sorry if you found that I'm asking stupid questions. But I'm new to asp.net and I'm facing a problem:

I'm writing a simple blog to learn asp.mvc, and I want to display an Edit link next to the blog Title if the user is logged in. Currently I have to add the currentUser object to Model and check the IsLogged properties to decide if I should display the Edit link or not. The problem is if there is no logged in user, I have to create an fake currentUser to insert to Model in other to make it work. What's asking is there is any other elegant way to do this. For example we can use [Authorize] attribute in Controller to allow access to an Action or not. There is any similar way to apply for the View ?

Upvotes: 2

Views: 3200

Answers (2)

Mose
Mose

Reputation: 1921

If you are using Forms authentication, this property already exists in the Request object :

Request.IsAuthenticated

In your view, you can solve you problem doing something like this :

<%  if(this.Request.IsAuthenticated)
    {
%>
    <%= Html.ActionLink("Edit", url - to - action) %>
<%  }
%>

But I think you real problem is checking that the current user is the one that can edit the current blog. In that case, you can do an extension method CanEdit on the ViewPage object :

<%  if(this.CanEdit(this.User))
    {
%>
    <%= Html.ActionLink("Edit", url - to - action) %>
<%  }
%>

The extension would look like something like that :

public static class ViewExtensions
{
    public static bool CanEdit(ViewPage view, MyUser user)
    {
        bool retour = false;

        if(principal != null)
        {
            // get your blog from the view
            Blog blog = view.ViewData["myBlog"];
            // check if the principal is the owner
            retour = (blog.Owner.Id == user.Id);
        }
        return retour;
    }
}

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422222

Make the IsLoggedIn a boolean property of the model itself. This way, you can have CurrentUser equal to null when IsLoggedIn is false. Your view would check IsLoggedIn and never call anything on CurrentUser if it's false. This way, NullReferenceException is circumvented.

You can also throw away the IsLoggedIn property altogether and check if a user has logged in directly by using CurrentUser != null.

Upvotes: 0

Related Questions