【问题标题】:How do I access FK values ​from view?如何从视图中访问 FK 值?
【发布时间】:2021-08-08 19:39:30
【问题描述】:

我有两个模型。我如何从视图中访问 FK 值或者我应该如何去做? HTML 页面什么也没有出现。

模型 1:

    public class Ogrenci
{
    public int OgrenciID { get; set; }
    public int OgrenciNumarasi { get; set; }
    public string Ad { get; set; }
    public string Soyad { get; set; }
    public string Bolum { get; set; }
    public short Sinif { get; set; }
    public string Yetenekler { get; set; }
    public string Sifre { get; set; }

    public List<Proje> Projeler { get; set; }
}

模型 2:

    public class Proje
{
    public int ProjeID { get; set; }
    public string ProjeAdi { get; set; }
    public string Aciklama { get; set; }
    public DateTime EklenmeTarihi { get; set; }

    public int OgrenciID { get; set; }
    public Ogrenci Ogrenci { get; set; }

}

控制器:

        public ActionResult Index()
    {
        return View(db.Projeler.ToList());
    }

查看:

@model IEnumerable<DonemProjesi.Models.Proje>

@{
    ViewBag.Title = "Index";
}
@Html.DisplayFor(modelItem => item.Ogrenci.Ad)    //the problem is here

【问题讨论】:

    标签: c# asp.net-mvc entity-framework model-view-controller


    【解决方案1】:

    尝试指定要包含在查询结果中的相关对象:

     return View(db.Projeler.Include(o => o.Ogrenci).ToList());
    

    Loading Related Entities

    【讨论】:

      【解决方案2】:

      试试这个

           public ActionResult Index()
          {
              return View(db.Ogrenci.Include(o => o.Projeler).FirstOrDefault());
          }
      
      @model DonemProjesi.Models.Ogrenci
      
      @{
          ViewBag.Title = "Index";
      }
      
      @Html.DisplayFor(m => m.Ad)  
      
      @for (int i = 0; i < Model.Projeler.Count; i+=1)
      {
       @Html.DisplayFor(model =>model.Projeler[i].ProjeAdi)
      }
      
      

      或者你的意思是这个

      
         public ActionResult Index()
          {
              return View(db.Projeler.Include(o => o.Ogrenci).ToList());
          }
      
      @model IEnumerable<DonemProjesi.Models.Proje>
      
      @{
          ViewBag.Title = "Index";
      }
      @for (int i = 0; i < Model.Count; i+=1)
      {
      @Html.DisplayFor(model =>model[i].ProjeAdi)
       @Html.DisplayFor(model => model[i].Ogrenci.Ad)
      }
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 2015-04-28
        • 2022-09-30
        • 1970-01-01
        相关资源
        最近更新 更多