0

Codes:

Create.cshtml:

@model StudentWeb.Models.ClassTable

@{
    ViewData["Title"] = "View";
}

<h1>View</h1>

<h4>ClassTable</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="ViewPage">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="ClassName" class="control-label"></label>
                <input asp-for="ClassName" class="form-control" />
                <span asp-validation-for="ClassName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

ViewPage.cshtml:

@model IEnumerable<StudentWeb.Models.ClassTable>

@{
    ViewData["Title"] = "View";
}

<h1>View</h1>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ClassName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.IdNavigation)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ClassName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.IdNavigation.ClassId)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </thead>
    <tbody>
</table>

I am getting an error on the ViewPage.cshtml page. Error:

enter image description here

My purpose in ViewPage.cshtml is to list all data. My entire file directory:

enter image description here

Right now I'm just trying to make the ClassTable. How can I solve this problem? Thanks in advance for your help. StudentClass is a different Form.

I would be glad if you help me. I watched a lot of videos, read documents but still couldn't do it.


ClassTableController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StudentWeb.Models;

namespace StudentWeb.Controllers
{
    public class ClassTablesController : Controller
    {
        private readonly StudentAppContext _context;

        public ClassTablesController(StudentAppContext context)
        {
            _context = context;
        }

        // GET: ClassTables
        public async Task<IActionResult> Index()
        {
            var studentAppContext = _context.ClassTables.Include(c => c.IdNavigation);
            return View(await studentAppContext.ToListAsync());
        }

        // GET: ClassTables/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables
                .Include(c => c.IdNavigation)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (classTable == null)
            {
                return NotFound();
            }

            return View(classTable);
        }

        // GET: ClassTables/Create
        public IActionResult Create()
        {
            ViewData["Id"] = new SelectList(_context.StudentClasses, "ClassId", "ClassId");
            return View();
        }

        // POST: ClassTables/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,ClassName")] ClassTable classTable)
        {
            if (ModelState.IsValid)
            {
                _context.Add(classTable);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["Id"] = new SelectList(_context.StudentClasses, "ClassId", "ClassId", classTable.Id);
            return View(classTable);
        }

        // GET: ClassTables/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables.FindAsync(id);
            if (classTable == null)
            {
                return NotFound();
            }
            ViewData["Id"] = new SelectList(_context.StudentClasses, "ClassId", "ClassId", classTable.Id);
            return View(classTable);
        }

        // POST: ClassTables/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,ClassName")] ClassTable classTable)
        {
            if (id != classTable.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(classTable);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClassTableExists(classTable.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["Id"] = new SelectList(_context.StudentClasses, "ClassId", "ClassId", classTable.Id);
            return View(classTable);
        }

        // GET: ClassTables/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.ClassTables == null)
            {
                return NotFound();
            }

            var classTable = await _context.ClassTables
                .Include(c => c.IdNavigation)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (classTable == null)
            {
                return NotFound();
            }

            return View(classTable);
        }

        // POST: ClassTables/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.ClassTables == null)
            {
                return Problem("Entity set 'StudentAppContext.ClassTables'  is null.");
            }
            var classTable = await _context.ClassTables.FindAsync(id);
            if (classTable != null)
            {
                _context.ClassTables.Remove(classTable);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ClassTableExists(int id)
        {
          return (_context.ClassTables?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}

HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using StudentWeb.Models;
using System.Diagnostics;

namespace StudentWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }
        public IActionResult ManageClass()
        {
            return View();
        }

        [HttpPost("AddClassDB")]
        public ActionResult AddClassDB(ClassTable _table)
        {
            
            return View("Index");
        }

        public IActionResult Create()
        {
            return View();
        }
        public IActionResult ViewPage()
        {
            return View();
        }
        public IActionResult ClassTableController()
        {
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Emir Bolat
  • 899
  • 3
  • 14
  • 37
  • Can you post the action code (from the controller file), seems that you are not passing the data while returning the View. – user1672994 Jul 30 '22 at 13:37
  • @user1672994 Hello. I added the codes by editing the topic. – Emir Bolat Jul 30 '22 at 13:46
  • Where are you passing the model in `ViewPage` action? You need to return the model; for ex - check the `Index` or `Details` method of `ClassTablesController ` – user1672994 Jul 30 '22 at 13:50
  • Hello. `
    ` I made a return to `Index` by adding the code. But it is not appended to SQL. Why could it be?
    – Emir Bolat Jul 30 '22 at 13:54
  • Something is amiss here. The error happens on the ViewPage.cshtml when you try to reference the Model instance. This instance should be passed from the controller when you call return _View(..modeldata..)_ where the view is by default the view with the same name of the controller action. But the ViewPage action in the HomeController doesn't return any data like you do in the Index action of the _ClassTables_ controller. – Steve Jul 30 '22 at 13:59
  • @Steve Hello. Frankly, I have no idea where I went wrong. I opened the project, created the pages, and then connected the database from the NuGet console. Finally, I right-clicked on the Controller folder and created a Controller in accordance with the Database table from Controller > MVC Controller with views, using entity framework. I have no clue where I went wrong. I'm just new to ASP.NET MVC. Sorry if I'm bothering you. – Emir Bolat Jul 30 '22 at 14:08
  • The ViewPage.cshtml is inside the HomeController. You should prepare the model there inside the ViewPage action because is from that action that your View will be called. And it needs the model data from there. – Steve Jul 30 '22 at 14:22

1 Answers1

1

you have to fix a ViewPage action by adding a model

public IActionResult ViewPage()
{
 var model = await _context.ClassTables.Include(c => c.IdNavigation).ToListAsync();
  return View(model);
}
Serge
  • 40,935
  • 4
  • 18
  • 45