Harriett Xing
Harriett Xing

Reputation: 49

DNN - getting user roles in javascript

I have an app in DotNetNuke. I would like to retrieve the list of user roles in header javascript, and check to see if it has "Administrators" role. What is the best way to do that?

Upvotes: 0

Views: 302

Answers (1)

VDWWD
VDWWD

Reputation: 35514

You could do something like this

using DotNetNuke.Common;
using System.Collections;
using DotNetNuke.Security.Roles;
using System.Web.Script.Serialization;

var RoleController = new RoleController();
var UserRoles = new List<RoleInfo>();

//for dnn 7.3 and lower
if (Globals.DataBaseVersion.Major < 7 || (Globals.DataBaseVersion.Major == 7 && Globals.DataBaseVersion.Minor < 3))
{
    UserRoles = RoleController.GetPortalRoles(PortalId).Cast<RoleInfo>().ToList();
}
else
{
    //for dnn 7.3 and higher
    UserRoles = RoleController.GetRoles(PortalId).ToList();
}

//convert the list to a json array
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(UserRoles.Select(x => x.RoleName));

//send the json to a client side function
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "allUserRoles", "setUserRoles('" + json + "')", true);

And the client side function. The variable json now is an Array with all the roles.

<script type="text/javascript">
    function setUserRoles(roles) {
        var json = JSON.parse(roles);
        for (var i = 0; i < json.length; i++) {
            console.log(json[i]);
        }
    }
</script>

Upvotes: 2

Related Questions