AnonyMouse
AnonyMouse

Reputation: 18650

MVC views making an item only visible to certain roles

I'm using MVC and in one of my view I have a dropdownlist I only want viewable by certain administrator.

I did this by:

@if (User.IsInRole("Administrator")) {
        @Html.DropDownListFor(...)
    }

However I have since been told this is not the way to go about it and you set the visibility of the dropdownlist in the viewModel.

Well the dropdownlist doesn't even exist in the view model. I have:

public SelectList AreaList { get; set; }

which is used to populate the dropdownlist.

Can anybody maybe give me some suggestions on what I might do to improve this?

Upvotes: 1

Views: 1044

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

I'm not what you've been told, but I think what they mean is that you would set a flag in the view model, such as bool showDropDown, then in your view you check the status of that flag.

However, there is no "right" way to do this. I think your first method is just fine.

Upvotes: 2

Daryl Teo
Daryl Teo

Reputation: 5495

I think what they mean is to put a flag in your ViewModel that specifies whether it should render the dropdownlist or not.

This changes

@if (User.IsInRole("Administrator")) {
    @Html.DropDownListFor(...)
}

To

@if (Model.ShouldDisplayAdminControls) {
    @Html.DropDownListFor(...)
}

This may be the case if your team isn't/doesn't want to use custom Membership providers, or to provide that option in the event that you want to move away from Membership (The IsInRole method causes your view to be coupled to your user management component)

Upvotes: 0

Related Questions