c# - 如何在 MVC View 中显示外键值

标签 c# asp.net-mvc azure

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

这是我的类(class):

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; }
}

这是在我的 Controller 中:

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 中此 ActionResult 中的“添加 View ”选项。默认 View (SearchIndex.cshtml) 将显示:

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

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

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

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

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

最佳答案

重写您的操作:

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);
    }

并使用 在 View 中

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

关于c# - 如何在 MVC View 中显示外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19238413/

相关文章:

android - MSAL Android :Missing required tokens of type: {0} while acquireToken

azure - 应用洞察 : SQL Dependency result code "-2"

c# - Excel 文件的格式与文件扩展名指定的格式不同(从 gridview 导出的 Excel)

c# - 反之foreach

c# - List<T>.Clear - 是否必须调用它?

c# - 在 ASP.NET MVC 中设置包含连字符的 html 属性时出现问题

asp.net-mvc - 我应该将 Controller 业务逻辑放在 MVC3 中的哪个位置

c# - 指定的转换无效。(数据表中的整数值)

c# - 具有键 'XXX' 的 ViewData 项的类型为 'System.Int32' 但必须为 'IEnumerable<SelectListItem>' 类型

azure - 发生传输级错误 - 指定的网络名称不再可用。 ( azure 突触)