Search code examples
razorroleswebmatrixrazor-2user-roles

Check Roles in Webmatrix


I add two users and two roles in the webpages_UsersInRoles. I am trying to check to role of the user logging into the application.

Here is my code:

var UserId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
var User = WebSecurity.CurrentUserName;
var db = Database.Open("ApplicationServices");
var stQueryString = "SELECT * FROM Table1 WHERE (UserId) = (UserId) ORDER BY SubmitDate DESC";
var data = db.Query(stQueryString, UserId);  
var grid = new WebGrid(data, rowsPerPage:20);

var AdminQueryString = "SELECT * FROM Table1 ORDER BY SubmitDate DESC";
var AdminData = db.Query(AdminQueryString);
var AdminGrid = new WebGrid(AdminData, rowsPerPage:20);

 <div id="Divgrid">
     @if (Roles.IsUserInRole(UserId, "admin") && (AdminData.Any())){
              @AdminGrid.GetHtml(
              tableStyle: "grid",
              headerStyle: "grid-header",
              footerStyle: "grid-footer",
              alternatingRowStyle: "grid-alternating-row",
              selectedRowStyle: "grid-selected-row",
              rowStyle: "grid-row-style",
              columns: AdminGrid.Columns(
                   AdminGrid.Column(header:"", format:@<a href="View/@item.Id">View</a>),
                   AdminGrid.Column(header:"", format:@<a href="Treatment/@item.Id">Treatment</a>),
                   AdminGrid.Column("Name", format:@<text>@item.ClientName</text>),
                   AdminGrid.Column("Date", format:@<text>@item.SubmitDate</text>))) }
        else if (Roles.IsUserInRole(UserId, "user") && (data.Any())) {
                 @grid.GetHtml(
                 tableStyle: "grid",
                 headerStyle: "grid-header",
                 footerStyle: "grid-footer",
                 alternatingRowStyle: "grid-alternating-row",
                 selectedRowStyle: "grid-selected-row",
                 rowStyle: "grid-row-style",
                 columns: grid.Columns(
                      grid.Column(header:"", format:@<a href="View/@item.Id">View</a>),
                      grid.Column(header:"", format:@<a href="Treatment/@item.Id">Treatment</a>),
                      grid.Column("Name", format:@<text>@item.ClientName</text>),
                      grid.Column("Date", format:@<text>@item.SubmitDate</text>))) }                    

   </div>

Here is the error I am getting:

CS1502: The best overloaded method match for 'System.Web.Security.Roles.IsUserInRole(string, string)' has some invalid arguments


Solution

  • The IsUserInRole takes two parameters, the first is the User name, not the user ID. You may be able to use WebSecurity.CurrentUserName in place of where you have UserID.

    One problem is the query needs to change to allow passing the username as a parameter:

    var stQueryString = "SELECT * FROM Table1 WHERE UserId = @0 ORDER BY SubmitDate DESC";
    

    The @0 indicates to take the parameter being passed in the Query.