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?
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)