Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object
I read up on the below thread and I couldn't find anything in regards to the issue I'm having. What is a NullReferenceException, and how do I fix it? My error is occurring on the View after attempting to load the page for the very first time. When I read through that page it looked to all be referencing the controller I've backtracked and they are all referencing something, so I'm not exactly sure what else I can do...
I am getting this error at
@foreach (string pg in Model.Paygroups)
in my view. I'm a little confused because I have Paygroups specified, and in my controller, I am sending the list to the model. I've tried messing with it for a couple of hours, but I'm not seeing where I'm not referencing the object. Any help is appreciated.
Controller
public class UpdateFilesController : Controller
{
// GET: Default
public ActionResult Edit()
{
return View();
}
[HttpPost]
public ActionResult Edit(string Paygroup)
{
var fullpath = Path.Combine(Server.MapPath("~/sourcefiles"), "paygroup.txt");
List<string> paygroupsList = new List<string> { System.IO.File.ReadAllText(fullpath) };
if (ModelState.IsValid)
{
paygroupsList.Add(Paygroup);
ViewBag.Message($"{Paygroup} succesfully added");
}
if (String.IsNullOrWhiteSpace(Paygroup))
{
UploadFiles model = new UploadFiles
{
Paygroups = paygroupsList
};
return View(model);
}
return View();
}
}
}
Model
public class UploadFiles
{
public List<string> Paygroups { get; set; }
[Required(ErrorMessage = "Please enter a paygroup.")]
public string PayGroup { get; set; }
}
View
@model WebApplication2.Models.UploadFiles
@{
ViewBag.Title = "Paygroup Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Update Paygroup</h2>
@using (Html.BeginForm("Edit", "UpdateFiles", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.PayGroup, new {@class = "control-label"})
@Html.EditorFor(m => m.PayGroup, new {htmlAttributes = new {@class = "form-control", placeholder = Html.DisplayNameFor(m => m.PayGroup)}})
@Html.ValidationMessageFor(m => m.PayGroup, "", new {@class = "text-danger"})
<input type="submit" value="Add" class="btn btn-default"/>
</div>
}
@if (ViewBag.Message != null)
{
{
<script type="text/javascript">
alert("@ViewBag.Message");
</script>
}
}
<table class="table table-striped">
<thead>
<tr>
<th>Paygroups</th>
</tr>
</thead>
<tbody>
<tr>
@foreach (string pg in Model.Paygroups)
{
<td>@pg</td>
}
</tr>
</tbody>
</table>