Click here to Skip to main content
15,889,266 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Problem

When display next record of EmployeeId i get error on line below :

HTML
<button id="BtnNext"onclick="location.href='@Url.Action("Next", "Employees",new {id=Model.EmployeeId })'" style="display:inline">Next</button>


NullReferenceException: Object reference not set to an instance of an object.

the line error found on view create of action create of Employees Controller .

Details

I have Employees controller have action Create and his view Create

ON View Create I put button Next to show next Row EmployeeId,EmployeeName,etc

but it show error above

Next button it must when click on it show next record and related data if exist

technology used asp.net core 2.1 visual studio 2017 sql server 2012

What I have tried:

C#
Employee Controller Code

    public class EmployeesController : Controller
        {
            private readonly IEmployees _context;
    
            public EmployeesController(IEmployees context)
            {
                _context = context;
            }
            public IActionResult Create()
            {
               return View(model);
            }
           [HttpPost]
            public async Task<IActionResult> Create(Employee employee)
            {
            return View(employee);
            }
            public ActionResult Next(int id)
            {
                var nextID = _context.GetAll().OrderBy(i => i.EmployeeId)
                         .SkipWhile(i => i.EmployeeId != id)
                         .Skip(1)
                         .Select(i => i.EmployeeId);
                ViewBag.NextID = nextID;
             
                return View("Create");
            }
    
      

         <div class="row">
                <div class="col-md-4">
    <button id="BtnNext"onclick="location.href='@Url.Action("Next", "Employees",new {id=Model.EmployeeId })'" style="display:inline">Next</button>
                 <form asp-action="Create">
        
                    <div asp-validation-summary="ModelOnly" class="text-danger"> 
              </div>
                    <div class="form-group">
                        <label asp-for="EmployeeId" class="control-label"></label>
                        <input asp-for="EmployeeId" class="form-control" />
                        <span asp-validation-for="EmployeeId" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="BranchCode" class="control-label"></label>
                        <input asp-for="BranchCode" class="form-control" />
                        <span asp-validation-for="BranchCode" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="EmployeeName" class="control-label"></label>
                        <input asp-for="EmployeeName" class="form-control" />
                        <span asp-validation-for="EmployeeName" class="text-danger"></span>
                    </div>
                    
                    <div class="form-group">
                        <input type="submit" value="Create" class="btn btn-default" />
                    </div>
                </form>
            </div>
        </div>
Posted
Updated 7-Jan-19 10:31am
Comments
Arkadeep De 7-Jan-19 13:27pm    
From where you are getting this Model.EmployeeId??
And set a null check on nextID before assign it to viewbag.
ahmed_sa 7-Jan-19 14:33pm    
so that how to solve problem can you tell me

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Comments
ahmed_sa 7-Jan-19 15:04pm    
this is full code for my controller employee
this is all my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using TAB.Data;
using TAB.Data.Dto;
using TAB.Service;


namespace TAB.Web.Controllers
{
public class EmployeesController : Controller
{
private readonly IEmployees _context;

public EmployeesController(IEmployees context)
{
_context = context;
}





// GET: Employees/Create
public IActionResult Create()
{
var model = new Employee();
model.EmployeeId = _context.GetAll().Max(Employee => Employee.EmployeeId) + 1;




return View(model);

}
public ActionResult Next(int id)
{
var nextID = _context.GetAll().OrderBy(i => i.EmployeeId)
.SkipWhile(i => i.EmployeeId != id)
.Skip(1)
.Select(i => i.EmployeeId);


ViewBag.NextID = nextID;

return View("Create");
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<iactionresult> Create(Employee employee)
{
if (ModelState.IsValid)
{

if (employee.EmployeeId <= 0)
{
await _context.InsertAsync(employee);
}

else
{
await _context.UpdateAsync(employee);
}

return RedirectToAction("Index");
}

return View(employee);

}


}
}
OriginalGriff 7-Jan-19 15:14pm    
Doesn't matter - we still can't run it under the same conditions you do, as we don't have access to you data.

Seriously, grab the debugger and see what you can find!
ahmed_sa 7-Jan-19 15:19pm    
nextID variable when put break point it have null value
OriginalGriff 7-Jan-19 16:17pm    
So now find out why.
What does GetAll return?
What's left after SkipWhile?
And so on.

We can't do that for you!
ahmed_sa 7-Jan-19 15:19pm    
and id =2
100+ Questions and counting!
Delivering bug free code is part of your job, may be it is time to learn how to track down bugs by yourself.
The error message is the result of a unique combination of your code, SQL server configuration, database ... that nobody can reproduce. You are the only one able to find the problem and correct it.
Quote:
NullReferenceException: Object reference not set to an instance of an object.

All we can say is that somewhere, an operation that return an object fails and the error message pops when you try to use that failed answer.
Use the debugger to see what your code is really doing.
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900