Reputation: 6477
I am trying to populate a SelectList:
new SelectList(db.StdOrgUser, "Id", "LastName", stdlibraryitem.StdOrgUserId);
The above is the straightforward approach in that "LastName" comes from the StdOrgUser table. However "StdOrgUser" is linked to "Aspnet_Membership" and therefore to "Aspnet_Users".
StdOrgUser (*-1) Aspnet_Membership (0..1 - 1) Aspnet_Users
I would like to access the "username" as stored in "Aspnet_Users" in the SelectList as opposed to "LastName". Is this possible and how?
Many thanks.
Upvotes: 0
Views: 51
Reputation: 26018
Don't use view bag, rather pass your data using a view model. Don't pass in your domain model, use a view model.
Lets start with your action method. Lets call it YourActionMethod
. It creates an instance of your view model and populates the user list with your users. How you populate your users in the sevice layer depends entirely up to you.
public ActionResult YourActionMethod()
{
YourViewModel viewModel = new YourViewModel
{
Users = userService.FindAll()
};
return View(viewModel);
}
Your view model can look like this (partial):
public class YourViewModel
{
public int UserId { get; set; }
public IEnumerable<User> Users { get; set; }
}
Create a domain model to represent your users. Your user domain model could look something like this:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
Your view (page) will receive your view model:
@model YourProject.ViewModels.Users.YourViewModel
And you drop down HTML markup will look like this:
@Html.DropDownListFor(
x => x.UserId,
new SelectList(Model.Users, "Id", "UserName", Model.UserId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.UserId)
Upvotes: 1