Return a different view than default - c#

This is homework, and I looked up similar questions, but I'm too code-challenged to know exactly how the syntax should be from the examples. This is an ASP.NET MVC app in Visual Studio, C#. This is what I get when I run it.
When I click on "Edit" or "Details" I want it to go to a page where a bike can be edited or details entered. Right now, it's going to the original assignment's index page, which has nothing to do with this, but the professor wants all of our assignments in one project:
Here is my BikeController code:
using MvcApplication3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class BikeController : Controller
{
//
// GET: /Bike/
List<Bike> bikes;
public BikeController()
{
if (bikes == null)
{
bikes = new List<Bike> {
new Bike(),
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road" }
};
}
}
public ActionResult Index()
{
return View(this.bikes);
}
private ActionResult View(Func<object> func)
{
throw new NotImplementedException();
}
//
// GET: /Bike/Details/5
public ActionResult Details(int id)
{
var currentBikes = bikes[id];
return View(currentBikes);
}
//
// GET: /Bike/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Bike/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Bike b = new Bike
{
Manufacturer = collection["Manufacturer"], Gears = int.Parse(collection["Gears"]), Frame = collection["Frame"]
};
bikes.Add(b);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Edit/5
public ActionResult Edit(int id)
{
return View(bikes.Where(b => b.BikeID == id).First());
}
//
// POST: /Bike/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Bike/Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Bike/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public int bike { get; set; }
}
}
Here is the Index in the Bike View:
#model IEnumerable<MvcApplication3.Models.Bike>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Manufacturer)
</th>
<th>
#Html.DisplayNameFor(model => model.Gears)
</th>
<th>
#Html.DisplayNameFor(model => model.Frame)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Manufacturer)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gears)
</td>
<td>
#Html.DisplayFor(modelItem => item.Frame)
</td>
<td>
#item.BikeID #item.Manufacturer #item.Gears #item.Frame
#Html.ActionLink("Edit", "Edit", new { id=item.BikeID }) |
#Html.ActionLink("Details", "Details", new { id=item.BikeID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.BikeID })
</td>
</tr>
}
</table>
</body>
</html>

You are never setting your BikeID, this needs to be unique
Also i'm have not sure what this is for
public int bike { get; set; }
in your BikeController try explicitly setting the id's
new Bike() { BikeID = 1},
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road", BikeID = 2 }
Also check your routing, in Global.asax there will
make sure routing is set up, this should be in either your global.asax or App_Start/RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Related

ASP.NET MVC Problem accessing data from third table

I have a problem to show data from table "Building_Address" in view of "Lease_Status" - it shows no records - only column names as on the pic
The diagram of tables and relations is:
the code of cshtml:
#model IEnumerable<test_ent_frame.Models.Lease_Status>
#{
ViewBag.Title = "Index"; }
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create") </p> <table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Room_Details.number)
</th>
<th>
#Html.DisplayNameFor(model => model.Building_Address.City)
</th>
<th></th>
</tr>
#foreach (var item in Model) { <tr>
<td>
#Html.DisplayFor(modelItem => item.Room_Details.number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building_Address.City)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id_Lease }) |
#Html.ActionLink("Details", "Details", new { id = item.Id_Lease }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id_Lease })
</td> </tr> }
</table>
The code of 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 test_ent_frame.Models;
namespace test_ent_frame.Controllers
{
public class Lease_StatusController : Controller
{
private testEntities db = new testEntities();
// GET: Lease_Status
public ActionResult Index()
{
var lease_Status = db.Lease_Status.Include(l => l.Room_Details);
return View(lease_Status.ToList());
}
// GET: Lease_Status/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
return View(lease_Status);
}
// GET: Lease_Status/Create
public ActionResult Create()
{
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room");
return View();
}
// POST: Lease_Status/Create
// Aby zapewnić ochronę przed atakami polegającymi na przesyłaniu dodatkowych danych, włącz określone właściwości, z którymi chcesz utworzyć powiązania.
// Aby uzyskać więcej szczegółów, zobacz https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id_Lease,Id_Room")] Lease_Status lease_Status)
{
if (ModelState.IsValid)
{
db.Lease_Status.Add(lease_Status);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// GET: Lease_Status/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// POST: Lease_Status/Edit/5
// Aby zapewnić ochronę przed atakami polegającymi na przesyłaniu dodatkowych danych, włącz określone właściwości, z którymi chcesz utworzyć powiązania.
// Aby uzyskać więcej szczegółów, zobacz https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id_Lease,Id_Room")] Lease_Status lease_Status)
{
if (ModelState.IsValid)
{
db.Entry(lease_Status).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// GET: Lease_Status/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
return View(lease_Status);
}
// POST: Lease_Status/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Lease_Status lease_Status = db.Lease_Status.Find(id);
db.Lease_Status.Remove(lease_Status);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
These are standard scaffolded files in visual studio
How to make it possible to show these records?
Debug:

The view 'Index' or its master was not found when i ran my project

this is the controller
namespace DemoforTesting.Controllers
{
public class ProductController : Controller
{
DefaultConnection db = new DefaultConnection();
// GET: Product
[HttpGet]
public ActionResult Index()
{
var products = db.Products.ToString();
return View(products);
}
// GET: Product/Details/5
[HttpGet]
public ActionResult Details(int id)
{
return View();
}
// GET: Product/Create
public ActionResult Create()
{
return View();
}
// POST: Product/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Product/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Product/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
my view is
#model IEnumerable<OnLineShoppingCart.Models.Product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Prod_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Unit_Price)
</th>
<th>
#Html.DisplayNameFor(model => model.ListPrice)
</th>
<th>
#Html.DisplayNameFor(model => model.Qty_on_Stock)
</th>
<th>
#Html.DisplayNameFor(model => model.Prod_Description)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Prod_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Unit_Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.ListPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.Qty_on_Stock)
</td>
<td>
#Html.DisplayFor(modelItem => item.Prod_Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
#Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ProductId })
</td>
</tr>
}
</table>
</body>
</html>
I get the error below and i tried everything and ran out ideas
Server Error in '/' Application.
The view 'SELECT
[Extent1].[ProductId] AS [ProductId],
[Extent1].[Prod_Name] AS [Prod_Name],
[Extent1].[Unit_Price] AS [Unit_Price],
[Extent1].[ListPrice] AS [ListPrice],
[Extent1].[Qty_on_Stock] AS [Qty_on_Stock],
[Extent1].[Prod_Description] AS [Prod_Description]
FROM [dbo].[Products] AS [Extent1]' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Product/SELECT
[Extent1].[ProductId] AS [ProductId],
[Extent1].[Prod_Name] AS [Prod_Name],
[Extent1].[Unit_Price] AS [Unit_Price], `enter code here
[Extent1].[ListPrice] AS [ListPrice],
[Extent1].[Qty_on_Stock] AS [Qty_on_Stock],
[Extent1].[Prod_Description] AS [Prod_Description]
FROM [dbo].[Products] AS [Extent1].aspx
I have right clicked on the Index method and created the view and still get this error can someone help me please I am new to MVC
MVC is failing to find the appropriate view as you're passing the wrong object to your view. At present, 'products' is just a string representation of db.Products, whereas your index view wants an IEnumerable<Product>
Change
[HttpGet]
public ActionResult Index()
{
var products = db.Products.ToString();
return View(products);
}
To
[HttpGet]
public ActionResult Index()
{
var products = db.Products.ToList(); //Or some other IENUM
return View(products);
}

Remember (persist) the filter, sort order and current page of Table in MVC 5 EF 6

So essentially I've done all my sorting, filtering and paging with the help of this tutorial, which has been very, very handy because I'm very new to this material. -
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
The 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 SunsUniversity.Models;
using SunsUniversity.DAL;
using PagedList;
using PagedList.Mvc;
namespace SunsUniversity.Controllers
{
public class StudentController : Controller
{
private SchoolContext db = new SchoolContext();
// GET: /Student/
public ViewResult Index()
{
var students = from s in db.Students
select s;
return View(students.ToList());
}
// GET: /Student/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// GET: /Student/Create
public ActionResult Create()
{
return View();
}
// POST: /Student/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,LastName,FirstMidName,EnrollmentDate")] Student student)
{
try
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(student);
}
// GET: /Student/Edit/5
public ActionResult Edit(int? id)
{
var model = TempData["Index"];
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: /Student/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,LastName,FirstMidName,EnrollmentDate")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
// GET: /Student/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: /Student/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
The Index:
#model IEnumerable<SunsUniversity.Models.Student>
#{
ViewBag.Title = "Students";
}
<h2>#ViewBag.Title</h2>
<p class="indexOptions">
#Html.ActionLink("Back", "Index", "Home") #Html.ActionLink("Create New", "Create")
</p>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstMidName)
</th>
<th>
#Html.DisplayNameFor(model => model.EnrollmentDate)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EnrollmentDate)
</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>
}
</tbody>
<tfoot>
<tr>
<th class="filterable"></th>
<th></th>
<th class="filterable"></th>
<th class="filterable"></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
#section Outro{
<script>
$(document).ready(function () {
var table = $('.table').DataTable();
$(".table tfoot th").each(function (i) {
if ($(this).hasClass("filterable")) {
var select = $('<select class="form-control"><option value="">Filter by</option></select>')
.appendTo($(this).empty())
.on('change', function () {
var val = $(this).val();
table.column(i)
.search(val ? '^' + $(this).val() + '$' : val, true, false)
.draw();
});
table.column(i).data().unique().sort().each(function (d, j) {
if (d.length > 0) {
select.append('<option value="' + d + '">' + d + '</option>');
}
});
}
});
});
</script>
}
Now my problem is:
My application users asked if it were possible for pages that contain a table to remember the filter, sort order and current page of the table(because when they click a table item to carry out a task and then go back to it they'd like it to be "as they left it")
Cookies seem to be the way forward, but how to get the page to load these and set them in the table before it makes its first data request is a little beyond me at this stage.
Does anyone have any experience with this kind of thing? Thanks!
Few things can be added at the end in the Index file
Save Preferences : called from $(window).unload(function(){ ... });
Load Preferences : called from $(document).ready(function(){ ... });
The easiest way would be to save the filters, ordering and page you want to go to in the session storage, a cookie, or viewbag. You would send the parameters on all calls back to the server on back to page. EF doesn't support the operation you want as it only cares about getting and setting data. You have to manage the pagination, sorting, and filtering in YOUR code.
The example you refer to handles this by using these parameters of PagedList( a nuget package)
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
The parameters are what they say they are and are sent back on each page you navigate to.
Full method code:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var students = from s in db.Students
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString)
|| s.FirstMidName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default: // Name ascending
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}

Table with information from database not showing up : System.NullReferenceException

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.

Foreign Key Just showing a number which is associated with the primary key

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.

Categories