Model returned null

JUAN MIGUEL C. NIETO 61 Reputation points
2022-11-15T15:19:10.4+00:00

260594-error.png

260633-controller.png

The program is capturing data and importing excel on SQL --- the importing of excel is a success but I keep getting this error.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Sreeju Nair 12,661 Reputation points
    2022-11-15T15:28:55.647+00:00

    Based on your post, I assume you are getting the error after posting the data. If yes, the reason is that you are not passing the student list to the view. Copy the code you use in the Get method to the Post handler and see whether it works.

    260634-image.png

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. JUAN MIGUEL C. NIETO 61 Reputation points
    2022-11-15T15:21:23.873+00:00

    Im new to debugging this kind of error so here's the whole controller hope someone can help me... Thanks

    public class StudentController : Controller
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BoardExamConnectionstring"].ConnectionString);
    OleDbConnection Econ;

        private void ExcelConn(string filepath)  
    
        {  
    
            string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filepath);  
    
            Econ = new OleDbConnection(constr);  
    
        }  
        private void InsertExceldata(string fileepath, string filename)  
    
        {  
    
            string fullpath = Server.MapPath("/excelfolder/") + filename;  
    
            ExcelConn(fullpath);  
    
            string query = string.Format("Select * from [{0}]", "Sheet1$");  
    
         
    
            OleDbCommand Ecom = new OleDbCommand(query, Econ);  
    
            Econ.Open();  
    
            DataSet ds = new DataSet();  
    
            OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);  
    
            Econ.Close();  
    
            oda.Fill(ds);  
    
            DataTable dt = ds.Tables[0];  
    
            SqlBulkCopy objbulk = new SqlBulkCopy(con);  
    
            objbulk.DestinationTableName = "dbo.Student";  
            objbulk.ColumnMappings.Add("StudentID", "StudentID");  
    
            objbulk.ColumnMappings.Add("FirstName", "FirstName");  
    
            objbulk.ColumnMappings.Add("LastName", "LastName");  
    
            objbulk.ColumnMappings.Add("Program", "Program");  
    
            objbulk.ColumnMappings.Add("YearGraduate", "YearGraduate");  
    
            objbulk.ColumnMappings.Add("BoardScore", "BoardScore");  
    
            con.Open();  
    
            objbulk.WriteToServer(dt);  
    
            con.Close();  
    
        }  
    
        StudentDAL _studentDAL = new StudentDAL();  
    
        // GET: Student  
         
        public ActionResult Index()  
        {  
      
    
            var studentList = _studentDAL.GetallStudents();  
    
            if (studentList.Count == 0)  
            {  
                TempData["InfoMessage"] = "Student data unavailable in the Database.";  
    
            }  
    
            return View(studentList);  
    
        }  
    
    
        [HttpPost]  
        public ActionResult Index(HttpPostedFileBase file)  
        {  
            string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);  
    
            string filepath = "/excelfolder/" + filename;  
    
            file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));  
    
            InsertExceldata(filepath, filename);  
             
              
            return View();  
        }  
    
        // GET: Student/Details/5  
        public ActionResult Details(int id)  
        {  
            try  
            {  
                var student = _studentDAL.GetStudentByID(id).FirstOrDefault();  
    
                if (student == null)  
                {  
                    TempData["InfoMessage"] = "Student unavailable with ID" + id.ToString();  
                    return RedirectToAction("Index");  
                }  
                return View(student);  
            }  
            catch (Exception ex)  
            {  
                TempData["ErrorMessage"] = ex.Message;  
                return View();  
    
            }  
        }  
    
        // GET: Student/Create  
        public ActionResult Create()  
        {  
            return View();  
        }  
    
        // POST: Student/Create  
        [HttpPost]  
        public ActionResult Create(Student student)  
        {  
            bool IsInserted = false;  
            try  
            {  
                if (ModelState.IsValid)  
                {  
                    IsInserted = _studentDAL.InsertStudent(student);  
                    if (IsInserted)  
                    {  
                        TempData["SuccessMessage"] = "Student data saved successfully!";  
                    }  
                    else  
                    {  
                        TempData["ErrorMessage"] = "Unable to save student data.";  
                    }  
                }  
                return RedirectToAction("Index");  
            }  
            catch (Exception ex)  
            {  
                TempData["ErrorMessage"] = ex.Message;  
                return View();  
    
            }  
    
        }  
    
        // GET: Student/Edit/5  
        public ActionResult Edit(int id)  
        {  
            var students = _studentDAL.GetStudentByID(id).FirstOrDefault();  
    
            if (students == null)  
            {  
                TempData["InfoMessage"] = "Student unavailable with ID" + id.ToString();  
                return RedirectToAction("Index");  
            }  
            return View(students);  
        }  
    
        // POST: Student/Edit/5  
        [HttpPost, ActionName("Edit")]  
        public ActionResult UpdateStudent(Student student)  
        {  
            try  
            {  
                if (ModelState.IsValid)  
                {  
                    bool IsUpdated = _studentDAL.UpdateStudent(student);  
    
                    if (IsUpdated)  
                    {  
                        TempData["SuccessMessage"] = "Student data updated successfully!";  
                    }  
                    else  
                    {  
                        TempData["ErrorMessage"] = "Unable to update student data.";  
                    }  
                }  
                return RedirectToAction("Index");  
            }  
            catch (Exception ex)  
            {  
                TempData["ErrorMessage"] = ex.Message;  
                return View();  
    
            }  
    
        }  
    
        // GET: Student/Delete/5  
        public ActionResult Delete(int id)  
        {  
            try  
            {  
                var student = _studentDAL.GetStudentByID(id).FirstOrDefault();  
    
                if (student == null)  
                {  
                    TempData["InfoMessage"] = "Student unavailable with ID" + id.ToString();  
                    return RedirectToAction("Index");  
                }  
                return View(student);  
            }  
            catch (Exception ex)  
            {  
                TempData["ErrorMessage"] = ex.Message;  
                return View();  
    
            }  
        }  
    
        // POST: Student/Delete/5  
        [HttpPost, ActionName("Delete")]  
        public ActionResult DeleteConfirmation(int id)  
        {  
            try  
            {  
                string result = _studentDAL.DeleteStudent(id);  
    
                if (result.Contains("deleted"))  
                {  
                    TempData["SuccessMessage"] = result;  
                }  
                else  
                {  
                    TempData["ErrorMessage"] = result;  
                }  
    
                return RedirectToAction("Index");  
            }  
            catch (Exception ex)  
            {  
                TempData["ErrorMessage"] = ex.Message;  
                return View();  
    
            }  
    
    
        }  
    }  
    

    }

    0 comments No comments

  2. JUAN MIGUEL C. NIETO 61 Reputation points
    2022-11-15T15:22:00.46+00:00

    I doubled checked and I returned all but the error keeps popping..

    0 comments No comments

  3. AgaveJoe 30,126 Reputation points
    2022-11-15T16:14:49.51+00:00

    The error clearly indicates the Model is empty. The only action that passes a model to the View is the Index action. I assume the error happens after uploading the Excel file to the Post method. Your Post method does not pass a model to the view. Either redirect to the Index action or populate the model in the Post action and pass it to the view.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.