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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With