简体   繁体   中英

Display values for a foreign key property in a model asp.net mvc5

I have a Society model in my application as such that uses a standard ApplicationUser object as it's "owner" as below:

public class Society
{

    public int id { get; set; }

    [DataType(DataType.Text)]
    [DisplayName("Society Name")]
    [Required(ErrorMessage = "Society Name is required")]
    [StringLength(50, ErrorMessage = "Maximum of 100 characters")]
    public String societyName { get; set; }

    public String owner { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime dateCreated { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime dateLastUpdated { get; set; }

    [DataType(DataType.Text)]
    [DisplayName("Where is your Society based?")]
    [Required(ErrorMessage = "Location is required")]
    [StringLength(50, ErrorMessage = "Maximum of 100 characters")]
    public String location { get; set; }

    public virtual ApplicationUser User { get; set; }


    public int countMembers() {
       // to come...
    }

    public void transferOwnershipTo() {
        // to come...
    }
}

I want to display the email property of the standard ApplicationUser as the owner of the society in my view as below:

<td>
   @Html.DisplayFor(modelItem => item.User.Email)
</td>

However is displaying nothing in my view. Absolutely empty. However, the intellisense is picking it up as I type "item dot User dot email".

If I try

<td>
   @Html.DisplayFor(modelItem => item.owner)
</td>

... then I get the guid (eg 34dgh5-fegre3-235 etc) of the owner.

Can someone point out what I need to get the item.User.Email foreign key property to work please?

Thanks.

...... Controller added below ......

public class SocietiesController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Societies
    public ActionResult Index()
    {
        return View(db.Societies.ToList());
    }

Were you able to resolve this? I'm having a very similar problem, but my controller is configured a bit differently, as my issue is for the details page... However, I have this working on my index page. try the following:

    public ActionResult Index()
    {
         var societylist = db.Societies.Include(x => x.TABLENAME);
         return View(societylist.ToList());
    }

where TABLENAME is whatever your table the email address data is housed in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM