0

I've read many articles which they state that querying should not be placed in the Controller, but I can't seem to see where else I would place it.

My Current Code:

public class AddUserViewModel 
{        
    public UserRoleType UserRoleType { get; set; }
    public IEnumerable<SelectListItem> UserRoleTypes { get; set; }

}

public ActionResult AddUser()
    {
        AddUserViewModel model = new AddUserViewModel()
        {

            UserRoleTypes = db.UserRoleTypes.Select(userRoleType => new SelectListItem
            {
                Value = SqlFunctions.StringConvert((double)userRoleType.UserRoleTypeID).Trim(),
                Text = userRoleType.UserRoleTypeName
            })
        };
        return View(model);  
    }

The View:

<li>@Html.Label("User Role")@Html.DropDownListFor(x => Model.UserRoleType.UserRoleTypeID, Model.UserRoleTypes)</li>

How do I retain the View Model and Query and exclude the User Type that should not show up?

tereško
  • 58,060
  • 25
  • 98
  • 150
xivo
  • 2,054
  • 3
  • 22
  • 37
  • How often are your role types going to change? In the past I've tackled this by using a custom HtmlHelper and creating my own "UserRoleDropdownFor" method which uses application caching to manage the list of roles and uses the built in DropDownListFor internally to allow the selection of a role. If you need multi-select you could also use the ListBoxFor helper and create a UserRoleMultiSelectFor helper. These methods work best when the list of options won't change often OR that you can clear the cache on an as-needed basis if changes are made to the role list. – Nick Bork May 08 '12 at 20:28
  • The dropdown won't change often, I'm trying to just retain the View Model structure. I have read that querying should not be done via the Controller, but in the ViewModels, but I am just missing something or I'm not seeing what I should do to make that work. – xivo May 08 '12 at 20:38

2 Answers2

1

I think that you are doing it just fine.

Any way... all you can do to remove the querying logic from controller is having a ServiceLayer where you do the query and return the result.

The MVC pattern here is used correctly... what your are lacking is the other 2 layers (BusinessLayer and DataAccessLayer)... since ASP.NET MVC is the UI Layer.

UPDATE, due to comment:

Using var userroletypes = db.UserRoleTypes.Where(u=> u.UserRoleType != 1); is OK, it will return a list of UserRoleType that satisfy the query.

Then, just create a new SelectList object using the userroletypes collection... and asign it to the corresponding viewmodel property. Then pass that ViewModel to the View.

BTW, I never used the db.XXXX.Select() method before, not really sure what it does... I always use Where clause.

SECOND UPDATE: A DropDownList is loaded from a SelectList that is a collection of SelectItems. So you need to convert the collection resulting of your query to a SelectList object.

var userroletypes = new SelectList(db.UserRoleTypes.Where(u=> u.UserRoleType != 1), "idRoleType", "Name");

then you create your ViewModel

var addUserVM = new AddUserViewModel();
addUserVM.UserRoleTypes = userroletypes;

and pass addUserVM to your view:

return View(addUserVM ); 

Note: I'm assuming your ViewModel has a property of type SelectList... but yours is public IEnumerable<SelectListItem> UserRoleTypes { get; set; } so you could change it or adapt my answer.

Romias
  • 13,783
  • 7
  • 56
  • 85
  • I believe you have misunderstood me. I am trying to find out how to do a custom query and keep the structure. `var model = db.Where(u=> u.UserRoleType != 1); // Not sure if I wrote this correctly, but this is an example` – xivo May 08 '12 at 20:05
  • `db` is just a declaration of my entity. `StudentSchedulingEntities db = new StudentSchedulingEntities();` Also, I'm not sure what you mean by "Then, just create a new SelectList object using the userroletypes collection... and asign it to the corresponding viewmodel property. Then pass that ViewModel to the View." – xivo May 08 '12 at 20:35
  • I thought it stand for "database" and was the context class in EntityFramework or something like that. – Romias May 08 '12 at 20:38
  • Yes, that is my database declaration of the auto generated model/dbcontext. – xivo May 08 '12 at 20:41
  • Hope this is a bit cleaner now. – Romias May 08 '12 at 21:22
  • I actually thought of that your solution and it works great, but is this correct for a View Model Pattern or am I misunderstanding the pattern? I thought we should not put linq in the Controller. – xivo May 08 '12 at 21:43
  • It depends: if you have a ServiceLayer where you handle all your business logic and data access, the Linq code should be moved to there. But if you just have all your logic in MVC and don't want to pollute your controllers, you can always have a controller helper class where you can do the logic. Then just use MyHelper.GetMyRoleTypes() and that way you remove linq from controller. But you are not broking the pattern by querying in the controller. – Romias May 08 '12 at 21:48
  • Thanks Romias, I'll look up service layers. I am not completely familiar with all the terms just yet. Do you know of any good articles I could read up on? – xivo May 08 '12 at 22:00
  • It is just a matter of a 3 tier standard development: a layer where you place UI logic (you use MVC here), other layer where you place all the logic associated with your business rules and that could be exposed to your MVC via WebServices for example, and other tier that access the database (here you are using EntityFramework). So if you need more info, just search for "3 tier ASP.NET MVC"... for example here: http://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En – Romias May 09 '12 at 00:42
0

I don't see anything wrong with your code other than this db instance that I suppose is some concrete EF context that you have hardcoded in the controller making it impossible to unit test in isolation. Your controller action does exactly what a common GET controller action does:

  1. query the DAL to fetch a domain model
  2. map the domain model to a view model
  3. pass the view model to the view

A further improvement would be to get rid of the UserRoleType domain model type from your view model making it a real view model:

public class AddUserViewModel 
{
    [DisplayName("User Role")]
    public string UserRoleTypeId { get; set; }

    public IEnumerable<SelectListItem> UserRoleTypes { get; set; }
}

and then:

public ActionResult AddUser()
{
    var model = new AddUserViewModel()
    {
        UserRoleTypes = db.UserRoleTypes.Select(userRoleType => new SelectListItem
        {
            Value = SqlFunctions.StringConvert((double)userRoleType.UserRoleTypeID).Trim(),
            Text = userRoleType.UserRoleTypeName
        })
    };
    return View(model);  
}

and in the view:

@model AddUserViewModel 
<li>
    @Html.LabelFor(x => x.UserRoleTypeId)
    @Html.DropDownListFor(x => x.UserRoleTypeId, Model.UserRoleTypes)
</li>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • How would I add a custom query in there? I'm trying to add some type of linq query to my viewmodel, but I'm not sure how I am suppose to do that without breaking the viewModel. – xivo May 08 '12 at 19:59