'IEnumerable' does not contain a definition for 'ImageName' and no accessible extension method 'ImageName' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?
Is the current error I am getting, However the way im going about this seems to be wrong if anyone can help or point me in the right direction it would be appreciated. (Aslo I am using .net core 2.1 since my school computers do not support later versions :/)
Here is the view:
#model IEnumerable<Lab2Phase1.Models.Car>
#{
ViewData["Title"] = "Index";
}
<strong>Index</strong>
<p>
<a asp-action="Create">Create New</a>
</p>
<div class="col-md-8">
<form action="/Cars" method="post">
#Html.TextBox("search")
<input type="submit" />
</form>
</div>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
<th>
#Html.DisplayNameFor(model => model.TopSpeed)
</th>
<th>
#Html.DisplayNameFor(model => model.ImageName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model)
</td>
<td>
#Html.DisplayFor(modelItem => item.TopSpeed)
</td>
<td>
<img src="~/Content/images/#Html.DisplayFor(modelItem => modelItem.ImageName)" style="height:200px;width:200px;"/>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are you sure to delete?')" })
</td>
</tr>
}
</tbody>
</table>
Here is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lab2Phase1.Models;
using Microsoft.AspNetCore.Mvc;
using Lab2Phase1.CarsContext;
using System.Collections.Specialized;
using System.Drawing;
namespace Lab2Phase1.Controllers
{
public class CarsController : Controller
{
EFDataContext _dbContext = new EFDataContext();
public IActionResult Cars()
{
var data = this._dbContext.Cars.ToList();
return View(data);
}
[HttpPost]
public IActionResult Cars(string search)
{
Console.WriteLine("boot");
//search = Request.Form["search"].ToString();
var data = _dbContext.Cars.Where(c => c.Model.Contains(search));
return View(data);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create([Bind("Id,Model,TopSpeed,ImageName")]Car model)
{
ModelState.Remove("Id");
model.Model = Request.Form["Model"];
model.TopSpeed = Request.Form["TopSpeed"];
model.ImageName = Request.Form["ImageName"];
if (ModelState.IsValid)
{
_dbContext.Cars.Add(model);
_dbContext.SaveChanges();
return RedirectToAction("cars");
}
return View();
}
public IActionResult Edit(int id)
{
Car data = _dbContext.Cars.Where(p => p.Id == id).FirstOrDefault();
return View("Create", data);
}
[HttpPost]
public IActionResult Edit(Car model)
{
ModelState.Remove("Id");
model.Id = Int32.Parse(Request.Form["Id"]);
model.Model = Request.Form["Model"];
model.TopSpeed = Request.Form["TopSpeed"];
model.ImageName = Request.Form["ImageName"];
if (ModelState.IsValid)
{
_dbContext.Cars.Update(model);
_dbContext.SaveChanges();
return RedirectToAction("cars");
}
return View("Create", model);
}
public IActionResult Delete(int id)
{
Car data = _dbContext.Cars.Where(p => p.Id == id).FirstOrDefault();
if (data != null)
{
_dbContext.Cars.Remove(data);
_dbContext.SaveChanges();
}
return RedirectToAction("cars");
}
}
}
Here's the model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Lab2Phase1.Models
{
public class Car
{
[Key]
public int Id { get; set; }
public string Model { get; set; }
public string TopSpeed { get; set; }
public string ImageName { get; set; }
}
}
<img src="~/Content/images/#Html.DisplayFor(modelItem => modelItem.ImageName)" style="height:200px;width:200px;"/>
should be
<img src="~/Content/images/#(item.ImageName)" style="height:200px;width:200px;"/>
Assuming your ImageName is a file name with extention, available in that path.
Related
I am making a page and on this page, there is a table. I want to filter Name from the table. And I wrote code like this:
Index.cshtml:
#using StudentApp.Models.Entity
#model List<StudentTable>
#{
ViewData["Title"] = "Manage Student";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<h1>Manage Student</h1>
<br />
#using (Html.BeginForm("Index", "Students", FormMethod.Get))
{
<p>
<b>Student Name:</b> #Html.TextBox("p");
<input type="submit" value="Ara">
</p>
}
<table id="tbl1" class="table table-bordered">
<tr>
<th>
Student ID
</th>
<th>
Student Name
</th>
<th>
Student Class
</th>
<th>
Edit
</th>
<th>
Delete
</th>
</tr>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Id
</td>
<td>
#item.Name
</td>
<td>
#item.Class.ClassName // Error
</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
}
</tbody>
</table>
Add Student
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>
<script>
$('#tbl1').dataTable({});
</script>
StudentController.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StudentApp.Models.Entity;
using System.Linq;
namespace StudentApp.Controllers
{
public class StudentTableController : Controller
{
StudentDatabaseContext db = new StudentDatabaseContext();
public IActionResult Index(string p)
{
var degerler = from d in db.StudentTables select d;
if (!string.IsNullOrEmpty(p))
{
degerler = degerler.Where(m => m.Name.Contains(p));
}
return View(degerler.ToList());
}
[HttpGet]
public ActionResult AddStudent()
{
List<SelectListItem> GetClass = new List<SelectListItem>();
foreach (var item in db.ClassTables.ToList())
{
GetClass.Add(new SelectListItem { Text = item.ClassName, Value = item.Id.ToString() });
}
ViewBag.ClassList = GetClass;
return View(new StudentTable());
}
[HttpPost]
public ActionResult AddStudent(StudentTable st)
{
db.StudentTables.Add(st);
db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult Delete(int id)
{
var student = db.StudentTables.SingleOrDefault(i => i.Id == id);
db.StudentTables.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult EditStudent(int id)
{
var info = db.StudentTables.SingleOrDefault(i => i.Id == id);
List<SelectListItem> GetClass = new List<SelectListItem>();
foreach (var item in db.ClassTables.ToList())
{
GetClass.Add(new SelectListItem { Text = item.ClassName, Value = item.Id.ToString() });
}
ViewBag.ClassT = GetClass;
return View("EditStudent", info);
}
[HttpPost]
public ActionResult EditStudent(StudentTable p)
{
var StudentT = db.StudentTables.SingleOrDefault(i => i.Id == p.Id);
StudentT.Name = p.Name;
StudentT.ClassId = p.ClassId;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
StudentTable.cs:
using System;
using System.Collections.Generic;
namespace StudentApp.Models.Entity
{
public partial class StudentTable
{
public int Id { get; set; }
public string? Name { get; set; }
public int ClassId { get; set; }
public virtual ClassTable? Class { get; set; }
}
}
When I run the codes, I get the following error on the Index.cshtml page:
Why could this be? How can I fix the error? Thanks in advance for your help.
You need an eager loading for the StudentTable entities to load its related Class entities.
public IActionResult Index(string p)
{
...
return View(degerler
.Include(x => x.Class)
.ToList());
}
While Class property is nullable type in StudentTable, use ?. null-conditional operator to prevent accessing to inner property when the parent is null.
View
#item.Class?.ClassName
I am at a total loss. Everything seems correct. And when I look at the database, the correct number is being submitted. But when I go to list the data from the database, the Amount column in the database list is always the same number.
When you go to the deposit tab, the first number you put in is always the number that will be displayed. So if i enter $50, $50 will appear in the transaction tab. However, let's say if i go back and put $60. It will still say $50 in the transaction history tab, but in the database, it says $60. Why is it not displaying the number from the database?
Account controller:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using The_Bank_of_Cardinal.Areas.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using The_Bank_of_Cardinal.Models;
namespace The_Bank_of_Cardinal.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly TransactionConnection _tc;
private readonly UserManager<CardinalUser> userManager;
private readonly SignInManager<CardinalUser> signInManager;
private readonly DepositConnection _dc;
public AccountController(TransactionConnection tc, UserManager<CardinalUser> userManager, SignInManager<CardinalUser> signInManager, DepositConnection dc)
{
_tc = tc;
this.userManager = userManager;
this.signInManager = signInManager;
_dc = dc;
}
public IActionResult Index()
{
return View();
}
public IActionResult Transactions()
{
var results = _tc.TransactionHistory.ToList();
return View(results);
}
public IActionResult Test()
{
return View();
}
[HttpGet]
public IActionResult Deposit(string Id)
{
var resultss = _dc.AspNetUsers.Where(s => s.Id == Id).FirstOrDefault();
return View(resultss);
}
[HttpPost]
public IActionResult Deposit(DepositModel model, TransactionModel tm)
{
var resultss = _dc.AspNetUsers.Where(s => s.Id == model.Id).FirstOrDefault();
int test = model.AccountBalance + userManager.GetUserAsync(User).Result.AccountBalance;
tm.UserName = userManager.GetUserAsync(User).Result.UserName;
string name = tm.UserName;
tm.Description = "personal deposit";
tm.TransactionType = "Deposit";
tm.Amount = "$" + model.AccountBalance.ToString();
model.AccountBalance = test;
_tc.TransactionHistory.Add(tm);
_tc.SaveChanges();
_dc.AspNetUsers.Remove(resultss);
_dc.AspNetUsers.Add(model);
_dc.SaveChanges();
//_dc.AspNetUsers.
return Content("This is your info \n" +
$"Name: {name} \n" +
$"Description: {tm.Description} \n" +
$"type: {tm.TransactionType} \n" +
$"Amount {tm.Amount} \n");
}
public IActionResult Transfers()
{
return View();
}
}
}
Transaction view:
#model IEnumerable<The_Bank_of_Cardinal.Models.TransactionModel>
#{
ViewData["Title"] = "Transactions";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Transactions</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
#*<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.UserName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.TransactionType)
</th>
<th>
#Html.DisplayNameFor(model => model.Amount)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.TransactionType)
</td>
<td>
#Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>*#
<div class="container">
#if (Model != null)
{
<table class="table table-dark">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Transaction Type</th>
<th scope="col">Amount</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.UserName)</td>
<td>#Html.DisplayFor(modelItem => item.Description)</td>
<td>#Html.DisplayFor(modelItem => item.TransactionType)</td>
<td>#Html.DisplayFor(modelItem => item.Amount)</td>
<td>#Html.DisplayFor(modelItem => item.Date)</td>
</tr>
}
</tbody>
</table>
}
</div>
Deposit view:
#model The_Bank_of_Cardinal.Models.DepositModel
#{
ViewData["Title"] = "Deposit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Deposit</h1>
<h4>DepositModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Deposit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label hidden asp-for="Id" class="control-label"></label>
<input hidden asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AccountBalance" class="control-label">Amount</label>
<input asp-for="AccountBalance" class="form-control" value="0" />
<span asp-validation-for="AccountBalance" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Deposit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Deposit model:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using The_Bank_of_Cardinal.Areas.Identity.Data;
namespace The_Bank_of_Cardinal.Models
{
public class DepositModel
{
[Key]
public string Id { get; set; }
public int AccountBalance { get; set; }
}
}
Transaction model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace The_Bank_of_Cardinal.Models
{
public class TransactionModel
{
[Key]
public string UserName { get; set; }
public string Description { get; set; }
public string TransactionType { get; set; }
public string Amount { get; set; }
public DateTime Date { get; set; }
}
}
Deposit DbContext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace The_Bank_of_Cardinal.Models
{
public class DepositConnection : DbContext
{
public DepositConnection(DbContextOptions<DepositConnection> options) : base(options)
{
}
public DbSet<DepositModel> AspNetUsers { get; set; }
}
}
Transaction DbContext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace The_Bank_of_Cardinal.Models
{
public class TransactionConnection : DbContext
{
public TransactionConnection(DbContextOptions<TransactionConnection> options) : base(options)
{
}
public DbSet<TransactionModel> TransactionHistory { get; set; }
}
}
The class TransactionModel has for primary key the property UserName.
But you have several TransactionModel instances with the same UserName value. This is contradictory. Each TransactionModel primary key must be unique.
Change your TransactionModel class to something like:
public class TransactionModel
{
public int Id { get; set; } // This is the primary key.
public string UserName { get; set; }
public string Description { get; set; }
public string TransactionType { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
The property Id is your primary key. It will be automatically incremented. This is by convention. See: https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations#configuring-a-primary-key
and https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#primary-keys
Side note: The type of the property Amount should rather be decimal than string, so this is changed in the example above. In the same spirit, an enum would maybe be a better choice for the TransactionType property.
You will need of course to modify the code using the class TransactionModel in order to take into account its new definition.
You're using #Html.XXXFor() incorrectly.
When you want to use HTML-helpers for HTML <form> input binding from a collection in your ViewModel you need to use for(), not foreach() and you need to the [int index] indexer in the For() expression.
When you need to bind a form object / form model and pass extra data to your view, use ViewData for the one-way data and Model for the two-way data.
I think that ASP.NET MVC and ASP.NET Core's view-model and form-binding system needs a re-think, as it's just plain wrong to require the ViewModel object to also be the bound form model. In my own projects I have my own extensions over ASP.NET Core to allow me to use separate types/objects cleanly.
I can't fix your ActionLink items though
<tbody>
#for( int i = 0; i < this.Model.Count; i++ ) {
<tr>
<td>
#Html.DisplayFor( m => m[i].UserName )
</td>
<td>
#Html.DisplayFor( m => m[i].Description )
</td>
<td>
#Html.DisplayFor( m => m[i].TransactionType )
</td>
<td>
#Html.DisplayFor( m => m[i].Amount )
</td>
<td>
#Html.DisplayFor( m => m[i].Date )
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
Every time I launched webpage for Index I keep getting this error. I cannot figure out the issue. It might be something simple I am over looking. If anyone has an idea that would be very much appreciated. I am not sure if the error is from the paging or the search feature.
Here is the picture of the error it is on the index ActionResult
ScannerAssignment Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ScannerAssignmentList.Models;
using PagedList;
namespace ScannerAssignmentList.Controllers
{
public class ScannerAssignmentController : Controller
{
private ScannerAssignmentDb _db = new ScannerAssignmentDb();
// GET: ScannerAssignment
public ActionResult Index(int? page, string searchTerm = null)
{
var model =
_db.ScannerAssignment
.OrderByDescending(r => r.EmployeeName)
.Where(r => searchTerm == null || r.EmployeeName.Contains(searchTerm) || r.Model.Contains(searchTerm) || r.Department.Contains(searchTerm) || r.EmployeeNumber.ToString().Contains(searchTerm) || r.Serial.ToString().Contains(searchTerm))
.Select(r => new ScannerAssignmentModel
{
Id = r.Id,
EmployeeName = r.EmployeeName,
EmployeeNumber = r.EmployeeNumber,
Model = r.Model,
Serial = r.Serial,
Department = r.Department
});
// return View(model);
return View(model.ToPagedList(page ?? 1, 5));
}
// GET: ScannerAssignment/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ScannerAssignmentModel scannerAssignmentModel = _db.ScannerAssignment.Find(id);
if (scannerAssignmentModel == null)
{
return HttpNotFound();
}
return View(scannerAssignmentModel);
}
// GET: ScannerAssignment/Create
public ActionResult Create()
{
return View();
}
// POST: ScannerAssignment/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,EmployeeName,EmployeeNumber,Model,Serial,Department,Comments")] ScannerAssignmentModel scannerAssignmentModel)
{
if (ModelState.IsValid)
{
_db.ScannerAssignment.Add(scannerAssignmentModel);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(scannerAssignmentModel);
}
// GET: ScannerAssignment/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ScannerAssignmentModel scannerAssignmentModel = _db.ScannerAssignment.Find(id);
if (scannerAssignmentModel == null)
{
return HttpNotFound();
}
return View(scannerAssignmentModel);
}
// POST: ScannerAssignment/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,EmployeeName,EmployeeNumber,Model,Serial,Department,Comments")] ScannerAssignmentModel scannerAssignmentModel)
{
if (ModelState.IsValid)
{
_db.Entry(scannerAssignmentModel).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(scannerAssignmentModel);
}
// GET: ScannerAssignment/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ScannerAssignmentModel scannerAssignmentModel = _db.ScannerAssignment.Find(id);
if (scannerAssignmentModel == null)
{
return HttpNotFound();
}
return View(scannerAssignmentModel);
}
// POST: ScannerAssignment/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ScannerAssignmentModel scannerAssignmentModel = _db.ScannerAssignment.Find(id);
_db.ScannerAssignment.Remove(scannerAssignmentModel);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Here is the View for the Index ActionResult
#using PagedList;
#using PagedList.Mvc;
#model IPagedList<ScannerAssignmentList.Models.ScannerAssignmentModel>
#{
ViewBag.Title = "Index";
}
<br />
<div class="panel panel-primary">
<div class="panel-heading">
<h1 class="panel-title">Search Area</h1>
</div>
<div class="panel-body">
<div class="form-group">
<form method="get">
#Html.TextBox("searchTerm", null, new { #class = "form-control" })<span class="input-group-btn"></span>
<div class="panel-footer">
<button id="btnSearch"
class="btn btn-sm btn-primary">
<i class="glyphicon glyphicon-search"></i>
Search
</button>
<a href="#Url.Action("Index", "ScannerAssignment")" class="btn btn-sm btn-primary">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span>
Reset
</a>
<a href="#Url.Action("Create", "ScannerAssignment")" class="btn btn-sm btn-primary">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
Add
</a>
</div>
</form>
</div>
</div>
</div>
<p>
#Html.ActionLink("Add New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().EmployeeName)
</th>
<th>
#Html.DisplayNameFor(model => model.First().EmployeeNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.First().Model)
</th>
<th>
#Html.DisplayNameFor(model => model.First().Serial)
</th>
<th>
#Html.DisplayNameFor(model => model.First().Department)
</th>
<th>
#Html.DisplayNameFor(model => model.First().Comments)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmployeeNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model)
</td>
<td>
#Html.DisplayFor(modelItem => item.Serial)
</td>
<td>
#Html.DisplayFor(modelItem => item.Department)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comments)
</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>
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, searchterm = Request.QueryString["searchterm"] }),
new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation = true, DisplayItemSliceAndTotal = true })
ScannerAssignment Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ScannerAssignmentList.Models
{
public class ScannerAssignmentModel
{
[Key]
public int Id { get; set; }
public string EmployeeName { get; set; }
public int EmployeeNumber { get; set; }
public string Model { get; set; }
public string Serial { get; set; }
public string Department { get; set; }
public string Comments { get; set; }
}
}
ScannerAssignmentDb
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ScannerAssignmentList.Models
{
public class ScannerAssignmentDb :DbContext
{
public ScannerAssignmentDb()
: base("name=DefaultConnection")
{
}
public DbSet<ScannerAssignmentModel> ScannerAssignment{ get; set; }
}
}
So, I made a connection to a database, created a table and successfully added a "View", so that I can go to www.mysite.com/TableView and everything shows up correctly. (Generated with a razor "strongly-type view" against my database model. I used the edmx wizard to create the database connection, and that generated a separate controller aswell.
I then wanted to show the table in my index.cshtml file. I copied the code generated in the TableView view, into the correct in my index.cshtml, but it throws a System.NullReferenceException.
I cant quiet figure out why it wont work. It did work as a "standalone" view, but not when i paste it into another cshtml page?
I figured out it has something to do with the model, but why will it not work, when it worked in the other view.
Here is the code pasted into my index.cshtml from the working view :
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page-full-width cf">
<div class="content-module">
<div class="content-module-heading cf">
<h3 class="fl">Full width page</h3>
<span class="fr expand-collapse-text">Click to collapse</span>
<span class="fr expand-collapse-text initial-expand">Click to expand</span>
</div> <!-- end content-module-heading -->
<div class="content-module-main">
#model IEnumerable<WebEncode.Models.RunningJobsDb>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th>
#Html.DisplayNameFor(model => model.Publish)
</th>
<th>
#Html.DisplayNameFor(model => model.User)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.Publish)
</td>
<td>
#Html.DisplayFor(modelItem => item.User)
</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>
</div> <!-- end content-module-main -->
</div> <!-- end content-module -->
And here is my RunningJobsController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebEncode.Models;
namespace WebEncode.Controllers
{
public class RunningJobsController : Controller
{
private WebEncodeDBEntities db = new WebEncodeDBEntities();
//
// GET: /RunningJobs/
public ActionResult Index()
{
return View(db.RunningJobsDb.ToList());
}
//
// GET: /RunningJobs/Details/5
public ActionResult Details(int id = 0)
{
RunningJobsDb runningjobsdb = db.RunningJobsDb.Find(id);
if (runningjobsdb == null)
{
return HttpNotFound();
}
return View(runningjobsdb);
}
//
// GET: /RunningJobs/Create
public ActionResult Create()
{
return View();
}
//
// POST: /RunningJobs/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(RunningJobsDb runningjobsdb)
{
if (ModelState.IsValid)
{
db.RunningJobsDb.Add(runningjobsdb);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(runningjobsdb);
}
//
// GET: /RunningJobs/Edit/5
public ActionResult Edit(int id = 0)
{
RunningJobsDb runningjobsdb = db.RunningJobsDb.Find(id);
if (runningjobsdb == null)
{
return HttpNotFound();
}
return View(runningjobsdb);
}
//
// POST: /RunningJobs/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RunningJobsDb runningjobsdb)
{
if (ModelState.IsValid)
{
db.Entry(runningjobsdb).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(runningjobsdb);
}
//
// GET: /RunningJobs/Delete/5
public ActionResult Delete(int id = 0)
{
RunningJobsDb runningjobsdb = db.RunningJobsDb.Find(id);
if (runningjobsdb == null)
{
return HttpNotFound();
}
return View(runningjobsdb);
}
//
// POST: /RunningJobs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
RunningJobsDb runningjobsdb = db.RunningJobsDb.Find(id);
db.RunningJobsDb.Remove(runningjobsdb);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
And the model.
namespace WebEncode.Models
{
using System;
using System.Collections.Generic;
public partial class RunningJobsDb
{
public int Id { get; set; }
public string Title { get; set; }
public string Status { get; set; }
public string Publish { get; set; }
public string User { get; set; }
public byte[] Remaining { get; set; }
}
}
I do know there are quiet a few questions about System.NullReference but I could not find any describing my kind of problem (may indicate I'm actually doing it in a stupid way)
I found the solution. And I feel rather stupid. I did not think about controllers and views in the right manner. After I read that the HomeController is responsible for the Views in /Home folder the issue presented itself.
I then moved the content from my RunningJobs controller, to HomeController. This way I could deliver the database content to my "Home/Index.cshtml" page with the ActionResult Index () function inside the HomeController.
The code itself was correct, the problem was me not realising the structure of MVC.
My guess is you're not passing in the model when setting the ActionResult in your controller action. The code should look something like:
return View("ViewTable", < *instance of IEnumerable< RunningJobsDB > *>)
Cheers,
Marius
You should delete first row in the table.Because your model is IEnumerable<WebEncode.Models.RunningJobsDb> not just RunningJobsDb so you can't do this without foreach loop:
#Html.DisplayNameFor(model => model.Title)
here, model represents your IEnumerable, and it doesn't contain a Title property. You can use it with foreach,but you already doing it.just delete first line, it is redundant and cause the exception.
I want a way in which I can display the value of the Foreign key rather then displaying a number. For example I have the following view to show all reviews:
#model IEnumerable<Games.Models.tblReview>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ReviewID
</th>
<th>
Recomendation
</th>
<th>
AvoidOrBuy
</th>
<th>
Score
</th>
<th>
GameIDFK
</th>
<th>
UserName
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ReviewID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Recomendation)
</td>
<td>
#Html.DisplayFor(modelItem => item.AvoidOrBuy)
</td>
<td>
#Html.DisplayFor(modelItem => item.Score)
</td>
<td>
#Html.DisplayFor(modelItem => item.GameIDFK)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { id=item.ReviewID }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
I want a way in which the GameIDFK shows the name of the game rather then a number my controller to show this information is basic will show you here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Games.Models;
namespace Games.Controllers
{
public class ShowAllReviewsController : Controller
{
//
// GET: /ShowAllReviews/
public ActionResult Index()
{
using (var db = new gamezoneDBEntities())
{
return View(db.tblReviews.ToList());
}
}
//
// GET: /ShowAllReviews/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /ShowAllReviews/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ShowAllReviews/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ShowAllReviews/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /ShowAllReviews/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ShowAllReviews/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /ShowAllReviews/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Is there a way in which i can obtain the game Foreign Key as this site is going to be used for new coming gamers and I want tos how which games are good play dont want a user clicking on a review and seeing just a number and no game name.
Can you please help
EDIT:
I used the following in my view:
#Html.DisplayFor(modelItem => item.tblGame.GameName)
But it crashses and gives the following error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
EDIT 2:
namespace Games.Models
{
using System;
using System.Collections.Generic;
public partial class tblReview
{
public int ReviewID { get; set; }
public string Recomendation { get; set; }
public string AvoidOrBuy { get; set; }
public string Score { get; set; }
public int GameIDFK { get; set; }
public string UserName { get; set; }
public virtual tblGame tblGame { get; set; }
}
You might want to consider using ViewModel classes, but I think if you amend your controller to use something like
return View(db.tblReviews.Include("tblGame").ToList());
You would be able to use the property in your view as you have posted above.