我正在尽最大努力获得一个简单的 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 仅供参考。