HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

MVC app to associate users with roles

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
associatemvcappwithrolesusers

Problem

I'm a beginner to web programming and just started a MVC project from scratch. Because this will become a large project eventually, I would like to make sure that I'm doing things kind of right from the beginning.

The architecture is the following: ASP.NET 4.6, MVC 5, EF 6, Identity 2.0. I'm using EF Database First approach and Bootstrap 3.3.5. The solution is divided into 3 projects: Data (where I keep my .edmx and model classes), Resources (where I keep strings for localization purposes -and eventually images-), and Web (with my controllers, views, etc).

I'm going to point out a couple of examples in my code where I'm not sure about my approach. I have a navigation bar with an "Administration" link and two submenu links, "Users" and "Roles".

Users

When a user clicks on "Users", I'd like to show a table with four columns:

  • Username



  • Roles (string with the names of all roles assigned)



  • Assign Role (button that will take you to another form)



  • Remove Role (button that will take you to another form)



This is what the UserIndex.cshtml view looks like:

```
@model List
@{
ViewBag.Title = Resources.Users;
}

@Resources.Users



@Resources.User
@Resources.Roles





@foreach (var user in Model)
{


@user.UserName


@user.DisplayRoles()


@using (Html.BeginForm("UserAssignRole", "Admin", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Where(u => u.Id.Equals(user.Id)).FirstOrDefault().UserName)

}


@using (Html.BeginForm("UserRemoveRole", "Admin", new { ReturnUrl = ViewB

Solution

Well, there's a lot there. I'll give some feedback on the Users bit.

I wouldn't call DisplayRoles in cshtml either. I would use a view model for that page. It would have an int, UserId, and 2 strings, UserName and UserRoles, and the page would use a list or ienumerable of that view model. Then in your Get for the Index, create the view model from each user and build up the collection. Pretty straightforward using LINQ.

For the 2 buttons in your table, can't you just use ActionLink? Yes it makes sense to have Get and Post for same action. But your Get for assigning roles would just take the user Id. Your Post would accept your view model, then you don't have to change the name in order to make it unique.

Context

StackExchange Code Review Q#106712, answer score: 3

Revisions (0)

No revisions yet.