locked
Selecting data from two different tables and save to another table using drop down list-Object reference not set to an instance of an object. RRS feed

  • Question

  • User-164452226 posted

    Good day Tech Gurus,

    l want to use drop down list to select fields from two tables and save the data to another table. Here is what l have.

    1) From the Course Entity select CourseCode

        public class Course
        {
            [Key]
            public int CourseID { get; set; }
            public string CourseCode { get; set; }
            public string CourseName { get; set; }
        }

    2) From the IntakeDetail Entity select IntakeID

        public class IntakeDetail
        {
            public int Id { get; set; }
            [Key]
            public string IntakeID { get; set; }
            public string IntakeName { get; set; }
            public string CollegeID { get; set; }
        }
    

    3) The Entity to be populated

       public class StudentCourse
        {
            [Key]
            public int EnrollmentID { get; set; }
            public string StudentID { get; set; }
            public string CourseCode { get; set; }
            public string IntakeID { get; set; }
            [NotMapped]
            public List<Course> CourseList { get; set; }
                    [NotMapped]
                    public List<IntakeDetail> IntakeList  { get; set; }
    }

    4) My EFStudentCourseRepository

        public class EFStudentCourseRepository : IStudentCourseRepository
        {
            private EFDbContext context = new EFDbContext();
            public IEnumerable<StudentCourse> StudentCourses
            {
                get { return context.StudentCourses; }
            }
            public void SaveStudentCourse(StudentCourse studentCourse)
            {
    
                if (studentCourse.EnrollmentID == 0)
                {
                    context.StudentCourses.Add(studentCourse);
                }
                context.SaveChanges();
            }
        }

    5) My StudentCourseController

            [HttpPost]
    EFStudentCourseRepository repository = new EFStudentCourseRepository(); public ActionResult Save(StudentCourse studentCourse) { EFCourseRepository courseRepository = new EFCourseRepository(); studentCourse.CourseList = courseRepository.Courses.ToList<Course>(); EFIntakeRepository intakeRepository = new EFIntakeRepository(); studentCourse.IntakeList = intakeRepository.IntakeDetails.ToList<IntakeDetail>(); if (ModelState.IsValid) { repository.SaveStudentCourse(studentCourse); TempData["message"] = string.Format("Student successfully enorolled for {0} Course", studentCourse.CourseCode); return RedirectToAction("StudentSubjectList"); } else { // there is something wrong with the data values return View("studentCourse"); } }

    6) My Save View (In this view l was trying to use Drop down list to fetch the CourseCode by l need to do the same for IntakeID)

    @using (Html.BeginForm("Save", "StudentCourse", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>UserLogin</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.StudentID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.StudentID, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.StudentID, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @*@foreach (var c in Model.CourseCode)
            {
                @Html.Partial("CourseList", c)
    
            }*@
                @Html.LabelFor(x => Model.CourseCode, htmlAttributes: new { @class = "control-label col-md-2" })
    
                <div class="col-md-10">
                    @Html.DropDownListFor(Model => Model.CourseCode, new SelectList(Model.CourseList, "CourseCode", "CourseName"), "Select")
    
                    @Html.ValidationMessageFor(model => model.CourseCode, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.IntakeID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.IntakeID, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.IntakeID, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    

    7) Error Message l am getting

    Server Error in '/' Application.
    
    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.
    
    Source Error: 
    
    
    
    Line 34: 
    Line 35:             <div class="col-md-10">
    Line 36:                 @Html.DropDownListFor(Model => Model.CourseCode, new SelectList(Model.CourseList, "CourseCode", "CourseName"), "Select")
    Line 37: 
    Line 38:                 @Html.ValidationMessageFor(model => model.CourseCode, "", new { @class = "text-danger" })
      
    
     Source File:  C:\Users\TMATIWURE\source\repos\CollegeSys\CollegeSys.WebUI\Views\StudentCourse\Save.cshtml    Line:  36 

    Please Help, and it looks like l will need to use these drop down list to select from tables and save to another table in many parts of my project so l am stuck.

    Saturday, September 22, 2018 3:38 PM

Answers

  • User-271186128 posted

    Hi tmatiwure,

    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.

    The issue is related to the "Model.CourseList", might be it is empty. Please check your HttpGet Save method, make sure you have set values for the Course List.

    Please refer to the following code:

            [HttpGet]
            public ActionResult Save()
            {
                StudentCourse stu = new StudentCourse();
                //set values for the IntakeList, used to populate the dropdownlist.
                stu.IntakeList = new List<IntakeDetail>() {
                    new IntakeDetail() { IntakeID= "intake 101" , IntakeName = "Intake A" },
                    new IntakeDetail() { IntakeID = "intake 102", IntakeName = "Intake B" },
                    new IntakeDetail() { IntakeID= "intake 103" , IntakeName = "Intake C" }
                };
                stu.IntakeID = "intake 102"; //set default selected value
                //set value for the courseList
                stu.CourseList = new List<Course>()
                {
                    new Course(){ CourseID= 101, CourseName = "CA", CourseCode="C001"},
                    new Course(){ CourseID= 102, CourseName = "CB", CourseCode="C002"},
                    new Course(){ CourseID= 103, CourseName = "CC", CourseCode="C003"},
                };
                stu.CourseCode = "C002"; //set default selected value.
                return View(stu);
            }

    Code in the save view:

            <div class="form-group">
                @Html.LabelFor(x => Model.CourseCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(Model => Model.CourseCode, new SelectList(Model.CourseList, "CourseCode", "CourseName"), "Select")
    
                    @Html.ValidationMessageFor(model => model.CourseCode, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.IntakeID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(Model => Model.IntakeID, new SelectList(Model.IntakeList, "IntakeID", "IntakeName"), "Select")
                    @Html.ValidationMessageFor(model => model.IntakeID, "", new { @class = "text-danger" })
                </div>
            </div>

    Besides, according to your model, I suppose perhaps you want to achieve cascading dropdownlist to select course and Intake. If that is the case, I suggest you could refer to the following links:

    https://code.msdn.microsoft.com/Cascading-DropDownList-in-833683f9

    https://www.c-sharpcorner.com/article/creating-simple-cascading-dropdownlist-in-mvc/

    https://www.codeproject.com/Tips/883701/An-ASP-NET-MVC-Cascading-Dropdown-List

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 24, 2018 5:34 AM

All replies

  • User1120430333 posted

    Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. 

    The error message means that code in the program is trying to reference/use an object that is not there in memory it's a null value object -- not there.

    It follows basic Object Oriented Programing principles. 

    https://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/

    You should learn how to use the Visual Stuido debugger, set a breakpoint in the code, start single-stepping line by line, until you hit the line that blows up, use Quickwatch to determine what object is a null value, you determine why the object is a null value  and you fix the code. 

    It's called code debugging. 

    https://docs.microsoft.com/en-us/visualstudio/debugger/getting-started-with-the-debugger?view=vs-2017

    Saturday, September 22, 2018 4:46 PM
  • User-271186128 posted

    Hi tmatiwure,

    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.

    The issue is related to the "Model.CourseList", might be it is empty. Please check your HttpGet Save method, make sure you have set values for the Course List.

    Please refer to the following code:

            [HttpGet]
            public ActionResult Save()
            {
                StudentCourse stu = new StudentCourse();
                //set values for the IntakeList, used to populate the dropdownlist.
                stu.IntakeList = new List<IntakeDetail>() {
                    new IntakeDetail() { IntakeID= "intake 101" , IntakeName = "Intake A" },
                    new IntakeDetail() { IntakeID = "intake 102", IntakeName = "Intake B" },
                    new IntakeDetail() { IntakeID= "intake 103" , IntakeName = "Intake C" }
                };
                stu.IntakeID = "intake 102"; //set default selected value
                //set value for the courseList
                stu.CourseList = new List<Course>()
                {
                    new Course(){ CourseID= 101, CourseName = "CA", CourseCode="C001"},
                    new Course(){ CourseID= 102, CourseName = "CB", CourseCode="C002"},
                    new Course(){ CourseID= 103, CourseName = "CC", CourseCode="C003"},
                };
                stu.CourseCode = "C002"; //set default selected value.
                return View(stu);
            }

    Code in the save view:

            <div class="form-group">
                @Html.LabelFor(x => Model.CourseCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(Model => Model.CourseCode, new SelectList(Model.CourseList, "CourseCode", "CourseName"), "Select")
    
                    @Html.ValidationMessageFor(model => model.CourseCode, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.IntakeID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(Model => Model.IntakeID, new SelectList(Model.IntakeList, "IntakeID", "IntakeName"), "Select")
                    @Html.ValidationMessageFor(model => model.IntakeID, "", new { @class = "text-danger" })
                </div>
            </div>

    Besides, according to your model, I suppose perhaps you want to achieve cascading dropdownlist to select course and Intake. If that is the case, I suggest you could refer to the following links:

    https://code.msdn.microsoft.com/Cascading-DropDownList-in-833683f9

    https://www.c-sharpcorner.com/article/creating-simple-cascading-dropdownlist-in-mvc/

    https://www.codeproject.com/Tips/883701/An-ASP-NET-MVC-Cascading-Dropdown-List

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 24, 2018 5:34 AM
  • User-164452226 posted

    Thank you so much. So l need to specify a HttpGet and HttpPost for the Save action method? Your code is working fine, l just copied and pasted it. Now how do l modify your code so l can get CourseCode and IntakeID from the database tables? l am not going to cascade at the moment.

    Monday, September 24, 2018 9:37 AM
  • User-164452226 posted

    Ok, got it. l can now populate from the db. Thanks so much.

    Monday, September 24, 2018 1:07 PM
  • User1120430333 posted

    Ok, got it. l can now populate from the db. Thanks so much.

    You got what? Did you understand why you got the exception?

    Monday, September 24, 2018 6:57 PM