如何在MVC视图中显示外键值

时间:2013-10-08 03:08:45

标签: c# asp.net-mvc azure

我正在尽力让一个简单的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);
    }

现在,我必须说我正在使用此ActionResult中的Visual Studio 2012中的“添加视图”选项。默认的View(SearchIndex.cshtml)将显示:

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

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

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

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

我将此应用程序发布到Azure FYI。

2 个答案:

答案 0 :(得分:4)

重写你的行动:

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)

答案 1 :(得分: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;
        }
    }