2013-11-01 2 views
1

Im пытается заполнить данные в представлении из sql db. Я выбираю все рецепты из определенной страны ... O.k ... Я также хочу отобразить название страны в верхней части представления, но у меня возникают проблемы с возвратом результата в представление. Любые идеи, было бы весьма признателен ...вернуть правильные данные в mvc View

Heres мой код

@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

только для того, чтобы просто указать название страны. Я передал бы имя через сумку для просмотра. –

+0

Эй, это ... Пробовал. получение [...] [SELECT] [Extent1]. [country_id] FROM [dbo]. [recipeTbl] AS [Extent1] WHERE [Extent1]. [country_id] = @ p__linq__0 ,,,,, когда я выполняю var ctry = db.countryTbls.Where (country => country.id == Я бы); ViewBag.country = ctry.ToString(); // вернуть страну через сумку для просмотра –

ответ

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> 
+0

Эй! Спасибо за ответ. Теперь я получаю сообщение об ошибке System.Data.Entity.DynamicProxies.countryTbl_B0E08AAE9DC0BB3D52F84075A0E8FB0D1 ... в моей базе данных страна-столбец содержит строку, поэтому запрос c => c.country == id (int) дает мне ошибку, не может применяться к операторам типа string и int ??? –

+0

Упс. жаль, что я ошибся. Измените его на 'c.country.id == id' – WannaCSharp

+0

Я отредактировал свой ответ. – WannaCSharp

1

viewbag поле, которое является динамическим. вы можете установить его в любом типе, который вы хотите. Так что на контроллере

ViewBag.Country = ctry; 

затем на ваш взгляд

<label>@ViewBag.Country</label> 
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> 

Надеется, что это сработало.

Смежные вопросы