-2

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...

enter image description here

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>
Xiodrade
  • 113
  • 14
  • Is `Model` null? – BJ Myers Mar 20 '19 at 19:16
  • 1
    The proposed duplicate is a [canonical answer](https://meta.stackoverflow.com/questions/291992/what-is-a-canonical-question-answer-and-what-is-their-purpose), not for your exact problem, but the basic idea of "something somewhere is `null`; use the debugger to find it." If not `Model` then is the `Model.Paygroups` collection itself `null`? Even if not, the fact that it's the responsibility of the user of the `UploadFiles` class to create the `List<>` for `Paygroups` - rather than `UploadFiles` creating a `get`-only `List<>` itself - seems error-prone. – Lance U. Matthews Mar 20 '19 at 19:34
  • That...actually makes sense. I was creating the list in the post with the expectation that it would generate the list on load, but I was having a brain fluff forgetting post happens after the user hits the button... This resolved my issue. Thank you. – Xiodrade Mar 20 '19 at 19:41
  • In your code, `Paygroup` is just a string passed to the method by you which is then tested with `IsNullOrWhiteSpace`. The `Paygroups` must be a collection of strings since that is what you assign to it - which means it is something altogether different and perhaps even unrelated to `Paygroup`. Testing a string will not prevent a collection from being null. The dupe applies – Ňɏssa Pøngjǣrdenlarp Mar 20 '19 at 19:44

1 Answers1

0

After taking what Bacon said into consideration I resolved my issue by simply moving my list and referencing my model into my GET edit()

public class UpdateFilesController : Controller
{
    // GET: Default
    public ActionResult Edit()
    {
        var fullpath = Path.Combine(Server.MapPath("~/sourcefiles"), "paygroup.txt");
        List<string> paygroupsList = new List<string> { System.IO.File.ReadAllText(fullpath) };
        UploadFiles model = new UploadFiles
        {
            Paygroups = paygroupsList
        };
        return View(model);
    }
    [HttpPost]
    public ActionResult Edit(string Paygroup)
    {
        if (ModelState.IsValid)
        {
            var fullpath = Path.Combine(Server.MapPath("~/sourcefiles"), "paygroup.txt");
            System.IO.File.WriteAllText(fullpath, Paygroup);
            ViewBag.Message = ($"{Paygroup} succesfully added");
        }
        return RedirectToAction("Edit", "UpdateFiles");
    }
}
Xiodrade
  • 113
  • 14