我在想如何解决这个问题。我正在开发一个ASP.NET MVC应用程序
我有一个models
public class SearcherString
{
public int ID { get; set; }
public string Description { get; set; }
public virtual ICollection<Path> Path { get; set;
public SearcherString()
{
Path = new List<Path>();
}
}
public class Path
{
public int ID { get; set; }
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}我正在将它传递到我的Controller中(我正在将我的模型写入我的数据库,然后检索它)
public ActionResult Index()
{
return View(db.SearchersString.ToList()
}我有一个View,它有:
@model IEnumerable<App.Models.SearcherString>问题是在我的视图中,我无法显示来自路径模型的名称
我试着做:
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
@foreach (var item in Model)
{
foreach (var path in item.Path)
{
<th>
@Html.DisplayName(path.CategoryID.ToString())
</th>
<th>
@Html.DisplayName(path.CategoryName)
</th>
}
}
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
@foreach (var path in item.Path)
{
<td>
@Html.DisplayFor(modelItem => path.CategoryID)
</td>
<td>
@Html.DisplayFor(modelItem => path.CategoryName)
</td>
}
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>但我只有:

有人能帮我解决这个问题吗?
编辑:
这里有办法将Html.DisplayName更改为Html.DisplayNameFor吗?
@Html.DisplayName(path.CategoryID.ToString())发布于 2015-09-17 07:46:54
应该将导航属性包含到查询中:
public ActionResult Index()
{
return View(db.SearchersString.Include(c=>c.Path).ToList()
}发布于 2015-09-17 08:06:20
你的模型不正确。
public SearcherString()
{
Path = new List<Path>();
}这不是财产。这被视为一种方法,一种特殊的方法。它是一个构造函数。它创建一个空的Path对象。
如果你想有一对多的关系。您必须为此使用该属性并添加一个ID属性。
public int PathID {get; set;}
public virtual Path Path{get; set;}现在有了一个延迟加载属性,它将自动将Path类的ID属性保存到SearchString模型属性PathID中。
要获得PathID,特别需要在使用EntityFramework时调用EntityFramework函数,这很有可能是这样的。
public ActionResult Index(){
return View(db.SearchersString.Include(c=>c.Path).ToList();
}https://stackoverflow.com/questions/32624961
复制相似问题