1

我试图从 sql db 在视图中填充数据。我从特定国家/地区选择所有食谱...好吧..我还想在视图顶部显示国家/地区名称,但在将结果返回到视图时遇到问题。任何想法将不胜感激......

这是我的代码

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

    }
4

3 回答 3

1

viewbag 是一个动态的字段。您可以将其设置为您想要的任何类型。所以在你的控制器上

ViewBag.Country = ctry;

那么在你看来

<label>@ViewBag.Country</label>
于 2013-11-01T20:29:21.120 回答
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>
于 2013-11-01T20:30:32.390 回答
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>

希望它奏效了。

于 2013-11-01T20:31:12.427 回答