I'm using ASP.NET MVC 5 and SQL Server, and I'm trying to get a user-uploaded image that is stored within the database to display on the Index View of my ASP.NET page. However, the program keeps throwing the following error in Index.cshtml:
// Thrown @ "@foreach (var item in Model) {" (Index.cshtml , Line 27)
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
Now, I've gone through several similar answered questions on this site, but I can't seem to figure out what is wrong with my program (as there are so many possible reasons for a NullReferenceException to occur!), but I believe it has something to do with empleado.Photo being null or something along those lines.
Could someone please help me figure out what I am doing wrong? I'm relatively new to C# and very new to ASP.NET MVC, so I am completely lost as to what the problem is and I would really appreciate some help with this.
Here are the files that the problematic code must be in:
Index.cshtml
@model IEnumerable<POS.Models.Faculty>
@{
ViewBag.Title = "All Faculty";
}
<h2>All Faculty</h2>
<p>
@Html.ActionLink("Add a new faculty member", "Guardar")
</p>
<table class="table">
<tr>
<th width="400"><center>Photo</center></th>
<th width="800"><center>Organization Name</center></th>
<th width="500"><center>First Name</center></th>
<th width="300"><center>Last Name</center></th>
<th width="200"><center>Job Title</center></th>
<th width="250"><center>Email</center></th>
<th width="350"><center>Address</center></th>
<th width="500"><center>Phone Number</center></th>
<th width="600"><center>Plan Status</center></th>
<th width="600"><center>Plan Days</center></th>
<th width="500"></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
<img src=@item.Photo height="200" width="200" /><center></center>
</td>
<td>@item.Organization_Name</td>
<td>@item.First_Name</td>
<td>@item.Last_Name</td>
<td>@item.Job_Title</td>
<td>@item.Email</td>
<td>@item.Address</td>
<td>@item.Phone_Number</td>
<td>@Html.DisplayFor(modelItem => item.Meal_Plan_Status)</td>
<td>@item.Plan.Plan_Days</td>
<td>
@Html.ActionLink("Edit", "Editar", new { id = item.Employee_ID }) |
@Html.ActionLink("Details", "Details", new { id = item.Employee_ID }) |
@Html.ActionLink("Delete", "Eliminar", new { id = item.Employee_ID })
</td>
</tr>
}
</table>
FacultyController.cs
using POS.Datos;
using POS.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.IO ;
using System.Configuration ;
using System.Data.SqlClient ;
using System.Web.UI ;
using System.Web.UI.WebControls ;
using static POS.Datos.FacultyAdmin ;
using POS.Models ;
using System.Data;
namespace POS.Controllers
{
public class FacultyController : Controller
{
public ActionResult Index()
{
return this.View() ;
}
FacultyAdmin admin = new FacultyAdmin();
/*
// GET: Faculty
public ActionResult Index()
{
return View(admin.Consultar());
}
*/
[HttpGet]
public ActionResult Nuevo()
{
Faculty e = new Faculty();
ViewBag.Meal_Plan = GetPlanesSelect();
admin.Consultar();
return View();
}
public ActionResult Guardar() // HTTP GET
{
ViewBag.mensaje = "";
ViewBag.Meal_Plan = GetPlanesSelect();
return View();
}
[HttpPost]
[ActionName("Guardar")]
public ActionResult Guardar(Faculty empleado , HttpPostedFileBase image_file)
{
if (ModelState.IsValid)
{
// This line creates a new Faculty instance (e). //
// CafeteriaPOS_Entities holds the connection to the database "HOSTNAME.Cafeteria_POS". //
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
// admin is a FacultyAdmin object ; Consultar() returns the information in Faculties ([dbo].[Faculty]) as a non-trackable list from the database. //
admin.Consultar();
// This line adds a new Employee (empleado) to [dbo].[Faculty] in the database. //
context.Faculties.Add(empleado);
// This line saves any changes made to [dbo].[Faculty] in the database. //
if (image_file != null)
{
try
{
empleado.Photo = new byte[image_file.ContentLength] ;
image_file.InputStream.Read(empleado.Photo , 0 , image_file.ContentLength) ;
}
catch (NullReferenceException n)
{
}
}
else
{
image_file = null ;
}
context.SaveChanges();
// This line displays a message on the page when information is saved. //
ViewBag.mensaje = "Informacion Guardada";
// This line redirects the user to the Index. //
return RedirectToAction("Index");
}
// This line returns the Faculty View with all the information found in the empleado objects found within [dbo].[Faculty]. //
return View(empleado);
}
[HttpGet]
public ActionResult Editar(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
ViewBag.Meal_Plan = GetPlanesSelect();
return View(empleado);
}
[HttpPost]
[ActionName("Editar")]
public ActionResult Editar(Faculty empleado)
{
if (ModelState.IsValid)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
context.Entry(empleado).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(empleado);
}
public IEnumerable<SelectListItem> GetPlanesSelect()
{
using (Cafeteria_POSEntities Context = new Cafeteria_POSEntities())
{
return Context.Plans.Select(plan => new SelectListItem { Value = plan.Plan_Name, Text = plan.Plan_Name }).ToList();
}
}
[HttpGet]
public ActionResult Eliminar(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
return View(empleado);
}
[HttpPost]
[ActionName("Eliminar")]
public ActionResult EliminarConfirm(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
context.Faculties.Remove(empleado);
context.SaveChanges();
return RedirectToAction("Index");
}
/*
// Saves user-uploaded image to the database //
public string Upload_Image(HttpPostedFileBase image_file)
{
Random r = new Random() ;
String path = "-1" ;
int random = r.Next() ;
if (image_file != null && image_file.ContentLength > 0)
{
string extension = Path.GetExtension(image_file.FileName) ;
if (extension.ToLower().Equals(".jpg") || extension.ToLower().Equals(".jpeg") || extension.ToLower().Equals(".png"))
{
try
{
path = Path.Combine(Server.MapPath("~/Content/Images") , random + Path.GetFileName(image_file.FileName)) ;
image_file.SaveAs(path) ;
String image_connection = ConfigurationManager.ConnectionStrings["HOSTNAME.Cafeteria_POS"].ConnectionString ;
SqlConnection sql_connection = new SqlConnection(image_connection) ;
sql_connection.Open() ;
String sql_query = "INSERT INTO [dbo].[Faculty] ([Photo]) VALUES (@Photo)" ;
SqlCommand sql_command = new SqlCommand(sql_query , sql_connection) ;
sql_command.Parameters.AddWithValue("@Photo" , image_file) ;
sql_command.ExecuteNonQuery() ;
sql_connection.Close() ;
}
catch (Exception ex)
{
path = "-1" ;
}
}
else
{
Response.Write("<script>alert('Images may only be of the following formats: .jpg , .jpeg , and .png .');</script>") ;
}
}
else
{
Response.Write("<script>alert('Please select an image to upload!');</script>");
path = "-1" ;
}
return path ;
}
*/
}
}
Faculty.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace POS.Models
{
using System;
using System.Collections.Generic;
public partial class Faculty
{
public int Employee_ID { get; set; }
public string Organization_Name { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Job_Title { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone_Number { get; set; }
public string Meal_Plan { get; set; }
public bool Meal_Plan_Status { get; set; }
public byte[] Photo { get; set; }
public virtual Plan Plan { get; set; }
}
}
Faculty.cs
using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
namespace POS.Datos
{
public class FacultyAdmin
{
public void Guardar(Faculty Employee)
{
using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
{
context.Faculties.Add(Employee);
context.SaveChanges();
}
}
public IEnumerable<Faculty> Consultar()
{
using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
{
return context.Faculties.Include(p => p.Plan).AsNoTracking().ToList();
//AsNoTracking para no hacer copia en memoria porque no se hace ningun CRUD
}
}
public class Image_Object
{
public int Employee_ID { get; set; }
public string Photo { get; set; }
}
}
}