3

我正在尽最大努力获得一个简单的 MVC 应用程序来显示外键值,但我就是无法让它工作。

这是我的课程:

public partial class Kingdoms
{
    public Kingdoms()
    {
        this.Provinces = new HashSet<Provinces>();
    }

    [Key]
    public int KingdomID { get; set; }
    public string Kingdom { get; set; }
    public Nullable<int> KingdomNr { get; set; }
    public Nullable<int> IslandNr { get; set; }
    public Nullable<System.DateTime> Created { get; set; }
    public Nullable<System.DateTime> Modified { get; set; }
    public bool AtWar { get; set; }
    public string Stance { get; set; }

    public virtual ICollection<Provinces> Provinces { get; set; }
}

public partial class Provinces
{
    public Provinces()
    {
        this.ProvinceData = new HashSet<ProvinceData>();
    }

    [Key]
    public int ProvinceID { get; set; }
    public int KingdomID { get; set; }
    public string Province { get; set; }
    public string Race { get; set; }
    public Nullable<int> Land { get; set; }
    public Nullable<int> Networth { get; set; }
    public Nullable<System.DateTime> Created { get; set; }
    public Nullable<System.DateTime> Modified { get; set; }

    public virtual Kingdoms Kingdoms { get; set; }
    public virtual ICollection<ProvinceData> ProvinceData { get; set; }
}

这是在我的控制器中:

public ActionResult SearchIndex(int networthfrom = 0, int networthto = 0, int landfrom = 0, int landto = 0, int nwafrom = 0, int nwato = 0)
    {
        var provinces = from p in db.Provinces select p;
        return View(provinces);
    }

现在,我不得不说我正在使用 Visual Studio 2012 中的 Add View 选项从这个 ActionResult。默认视图 (SearchIndex.cshtml) 将显示:

@Html.DisplayFor(modelItem => item.KingdomID)

这将显示王国的ID。但我想显示来自 Kingdoms 类的字符串值 Kingdom。我尝试了以下方法:

@Html.DisplayFor(modelItem => item.Kingdoms.Kingdom)

但这只会产生:错误。处理您的请求时发生错误。

我正在将此应用程序发布到 Azure 仅供参考。

4

2 回答 2

5

重写你的动作:

public ActionResult SearchIndex(int networthfrom = 0, int networthto = 0, int landfrom = 0, int landto = 0, int nwafrom = 0, int nwato = 0)
    {
        var provinces = db.Provinces.Include(p=>p.Kingdoms);
        return View(provinces);
    }

并在视图中使用

@Html.DisplayFor(modelItem => item.Kingdoms.Kingdom)
于 2013-10-08T04:39:47.697 回答
0

假设您要显示table1HasForeignKey的所有列以及另一个名为Table2-has-referenced-PrimaryKey 的表的某些列。表table1HasForeignKey也有一个外键引用表Table2-has-referenced-PrimaryKey的主键。要显示两个表的连接,您可以按照以下步骤操作:

在控制器的动作中写入:

public ActionResult Details(int Id)
    {            
        BussinceLogicLayer.UploadedFileBLL uploadBLL = new BussinceLogicLayer.UploadedFileBLL();
        var details = uploadBLL.Details(Id).ToList();
        return View(details);
    }

其中方法uploadBLL.Details(int id)定义如下:

public List<table1HasForeinKey> Details(int Id)
    {
        using (Entities1 context = new Entities1())
        {
            var uploadList = context.table1HasForeinKey.Include("Table2-has-referenced-PrimaryKey").Where(x => x.PrimaryKeyInTable1 == Id).ToList();
            return uploadList;
        }
    }
于 2017-01-01T07:53:26.193 回答