我试图在sql db的视图中填充数据。我从特定的区域选择所有食谱... O.k ...我还想在视图的顶部显示国家名称,但我在将结果返回到视图时遇到问题。任何想法将不胜感激......
继承我的代码
@model IEnumerable<FoodB.recipeTbl>
<h2>************where i want to put the country title***************88</h2>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.recipe_title)
</th>
<th>
@Html.DisplayNameFor(model => model.ingredients)
</th>
<th>
@Html.DisplayNameFor(model => model.country_id)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.recipe_title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ingredients)
</td>
<td>
@Html.DisplayFor(modelItem => item.country_id)
</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>
这是我的控制器
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.Where(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.Where(country => country.id == id);
return View(query);
}
答案 0 :(得分:1)
viewbag是一个动态的字段。你可以把它设置成你想要的任何类型。所以在你的控制器上
ViewBag.Country = ctry;
然后在你看来
<label>@ViewBag.Country</label>
答案 1 :(得分:1)
使用SingleOrDefault
代替Where
,因为您只需要一个条目
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.SingleOrDefault(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.SingleOrDefault(c => c.id == id);
ViewBag.Country = ctry;
return View(query);
}
查看强>
<h1>ViewBag.Country </h1>
答案 2 :(得分:1)
您可以使用ViewBag。
控制器
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.Where(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.Where(country => country.id == id);
ViewBag.country = ctry.ToString();
return View(query);
}
视图
@model IEnumerable<FoodB.recipeTbl>
<h2>ViewBag.country</h2>
希望它有效。