Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Web.Mvc.WebViewPage<TModel>.Model.get returned null

Home Controller

public ActionResult Index()
{
    using (MvcDB dataBase = new MvcDB())
    {

    }
    return View();
}

public void DataDoldur()
{
    using (MvcDB dataBase = new MvcDB())
    {
        Kategori ktgr1 = new Kategori();
        ktgr1.KategoriAdi = "Spor";
        dataBase.Kategori.Add(ktgr1);

        dataBase.SaveChanges();
    }

}

Index.cshtml

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <div>
            <label>Kategori Seçiniz:</label>
        </div>
        <select name="Seçilen Kategori">
            @foreach (Kategori kategori in Model)
            {
               <option>@kategori.KategoriAdi</option> 
            }
        </select>
        <input type="submit" value="Haberleri Listele " />
    </div>
</body>
</html>

"System.Web.Mvc.WebViewPage.Model.get returned null" error I get it. what should I do? My database is ready but I cant use it. I think it is true, but does not work. How can I get the foreach to work? Not understanding this.

like image 602
Erman Avatar asked Aug 29 '17 17:08

Erman


1 Answers

Welcome to the community. The error is because you haven't defined Model in your View.

Try the following :
a) create a _Layout.cshtml file - it's like a master file under Views/Shared folder.

b) Put all your HTML in the layout and in the view files - have only the code that you need in the body.

c) Send a model from your get controller method.

d) Receive the model in your View and iterate in foreach (or) build a dropdown using HTML Helper

_Layout.cshtml :

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
   @RenderBody()
</body>
</html>

Index.cshtml :

@model <Your Model >
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
} 
  <div> 
      <div>
         <label>Kategori Seçiniz:</label>
      </div>
      <select name="Seçilen Kategori"> // Instead of using it this way, please go with @Html.DropDownListFor
                @foreach (Kategori kategori in Model)
                {
                   <option>@kategori.KategoriAdi</option> 
                }
       </select>
       <input type="submit" value="Haberleri Listele " />
   </div>

Home Controller :

public ActionResult Index()
{
    using (MvcDB dataBase = new MvcDB())
    {

    }
    return View(< YourModel > );
}

You need to fill your model and send it to the View like above .

like image 182
Vidiya Prasanth Pappannan Avatar answered Nov 09 '22 12:11

Vidiya Prasanth Pappannan