Reputation: 517
Im trying to populate data in a view from an sql db. Im selecting all recipes from a specific counry...O.k...I also want to display the country name at the top of the view but im having problems returning the result to the view. Any ideas would be greatly appreciated...
Heres my code
@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>
Here's my controller
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);
}
Upvotes: 1
Views: 211
Reputation: 1898
Use SingleOrDefault
instead of Where
since you are looking for one entry only
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);
}
View
<h1>ViewBag.Country </h1>
Upvotes: 1
Reputation: 1303
You can use the ViewBag.
The controller
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);
}
The view
@model IEnumerable<FoodB.recipeTbl>
<h2>ViewBag.country</h2>
Hope it worked.
Upvotes: 1
Reputation: 6423
viewbag is a field that is dynamic. you can set it to whatever type you want. So on your controller
ViewBag.Country = ctry;
then in your view
<label>@ViewBag.Country</label>
Upvotes: 1