0

So this is more of a 'Can I use it like that' question and 'Is it good practice or maybe I should do it different'. I'm specifically interested in Users. Let's say my app has a model called Tasks and each task has properties like this:

public class Task
{
    public int ID { get; set; }

    public string Name { get; set; }

    public ApplicationUser User { get; set; }

    public int? UserID { get; set; }  //Who's assigned to this Task
}

Is it okay to state users like this and the in controller get drop down list of them like this:

@using (var db = new ApplicationDbContext())
{
  @Html.DropDownList("UserID", new SelectList(db.Users, "Id", "UserName"))        
}

(Basically when creating a task I'd assign a User to it). Is it good practice? Maybe there are other better ways to use it?

1 Answer 1

1

First of all you should not use dbcontext instance in your cshtml page, You should do it either in controller,

You can assign users list to the viewbag in controller like

 var db = new ApplicationDbContext()
 ViewBag.Users = new SelectList(db.Users.ToList(),  "Id", "UserName"); 

and in cshtml you should bind like ,

@Html.DropDownList("User", ViewBag.Users)   
Sign up to request clarification or add additional context in comments.

8 Comments

why is that bad and why is this good? (I want to understand in depth)
@HighSepton accordingly design it is bad practice, you are tightly coupling your view with your business entities, actually you should pass viewmodel to the view, not actual business entity(i.e. Task)
okay, other than that is having User like that in the model alright or maybe it could be better?
@HighSepton your model of Task is alright it can have User and proper designed, but how you are binding with view is bad practice,
I kind of made up that on the spot, because my main thought was about the Model. I would do it with a ViewModel firstly and secondly I would do it like you suggested probably. Maybe I'd return a IEnumerable rather than a ViewBag
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.