2016-04-29 159 views
0

我沒有太多的編程經驗,我是MVC的新手。MVC從模型通過控制器傳遞對象到視圖

我想用實體框架從數據庫中提取一些數據並將其打印在視圖中。

這是我的模型:

public class Grad 
{ 
    public int ID { get; set; } 
    public string Naziv { get; set; } 
    public char KoordinataX { get; set; } 
    public char KoordinataY { get; set; } 
    public int BrojStanovnika { get; set; } 
} 
public class GradDBContext : DbContext 
{ 
    public DbSet<Grad> Gradovi { get; set; } 
} 

這是一個控制器:

private GradDBContext db = new GradDBContext(); 

    public ActionResult Index() 
    { 
     List<int> gradoviList = new List<int>(); 
     foreach (sea.Models.Grad g in db.Gradovi) 
     { 
      gradoviList.Add(g.ID); 
     } 
     ViewData["Gradovi"] = new SelectList(gradoviList); 
     return View(); 
    } 

,這是一個觀點:

@foreach (var item in ViewData["Gradovi"] as IEnumerable<int>) ---> error appears here as null reference exception 
      { 
       <p>item</p> 
      } 

我知道,我必須分析數據,但不知道我做錯了什麼

+0

感謝您的回答。我很傷心,我是編程和MVC的新手,對實體框架和那種東西還不太熟悉。這是我第一次嘗試從數據庫中打印某些東西。是的,只是試圖顯示一個ID列表 – Fale1994

回答

4

ViewData項目與關鍵"Gradovi"是typeof運算SelectList,因此將需要

@foreach (var item in ViewData["Gradovi"] as SelectList) 
{ 
    <p>@item.Value</p> // or @item.Text 

但是沒有點產生IEnumerable<SelectListItem>(這是什麼SelectList是),當你不需要它,你應該將模型傳遞給視圖。你在控制器代碼應該是

public ActionResult Index() 
{ 
    IEnumerable<int> model = db.Gradovi.Select(x => x.ID); 
    return View(model); 
} 

,並在視圖

@model IEnumerable<int> 
@foreach(var item in Model) 
{ 
    <p>@item</p> 
} 
1

您的代碼可以工作就像你擁有了它,但我要稍作修改,並給你一些指針。我正在提供一個基於我在你的帖子中看到的答案,而不是我認爲你想在以後階段實現的答案。有很多方法來實現目標,我會選擇我通常會用最簡單的方法:

public ActionResult Index() 
{ 
    // You will have a repository layer for this part 
    GradDBContext db = new GradDBContext(); 

    // Get a list of your items 
    List<Grad> gradovis = db.Gradovi.ToList(); 

    // I never work with view data, I just pass my view model to the view 
    // This way you now have more data to display on the screen (if you need more) 
    return View(gradovis); 
} 

然後你的觀點看起來是這樣的:

@model List<Project.Model.Grad> 

@foreach (var grad in Model) 
{ 
    <p>@grad.ID</p> 
} 
相關問題