Object reference not set to an instance of an object

JUAN MIGUEL C. NIETO 61 Reputation points
2022-11-29T14:01:38.77+00:00

I've returned all of my Get and Post controllers. But still, I'm having this kind of error. What am I missing?

Controller:
public ActionResult Data()
{
Excel1 products = GetProducts();
ViewBag.Message = "";
return View(products);
}

    public void DownloadFile(String file)  
    {  
        try  
        {  
            String filename = file;  
            String filepath = Server.MapPath("~/UploadedFile/" + filename);  

            Response.Clear();  
            Response.ClearHeaders();  
            Response.ClearContent();  
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);  
            Response.Flush();  

            Response.TransmitFile(filepath);  
            Response.End();  
            // HttpContext.ApplicationInstance.CompleteRequest();  
            ViewBag.Message = "";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = ex.Message.ToString();  
        }  


    }  

    [HttpPost]  
    public ActionResult Data(Excel1 obj)  
    {  
        try  
        {  
            string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss");  
            string finalPath = "\\UploadedFile\\" + strDateTime + obj.UploadFile.FileName;  

            obj.UploadFile.SaveAs(Server.MapPath("~") + finalPath);  
            obj.FilePath = strDateTime + obj.UploadFile.FileName;  
            ViewBag.Message = SaveToDB(obj);  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = ex.Message.ToString();  
        }  

         

        Excel1 products = GetProducts();  
        return View(products);  

    }  

    public string SaveToDB(Excel1 obj)  
    {  
        try  
        {  
            con = new SqlConnection(connectionString);  
            cmd = new SqlCommand();  
            con.Open();  
            cmd.Connection = con;  
            cmd.CommandType = System.Data.CommandType.StoredProcedure;  
            cmd.CommandText = "sp_AddFiles";  
            cmd.Parameters.AddWithValue("@FileN", obj.FileN);  
            cmd.Parameters.AddWithValue("@FilePath", obj.FilePath);  
            cmd.ExecuteNonQuery();  

            cmd.Dispose();  
            con.Dispose();  
            con.Close();  

            return "Saved Successfully";  
        }  
        catch (Exception ex)  
        {  
            return ex.Message.ToString();  
        }  

    }  


    public Excel1 GetProducts() //method   
    {  
        Excel1 products = new Excel1();  
        try  
        {  
            con = new SqlConnection(connectionString);  
            cmd = new SqlCommand("Select * from tblFiles", con);  
            con.Open();  
            adapter = new SqlDataAdapter(cmd);  
            DataTable dt = new DataTable();  
            adapter.Fill(dt);  

            adapter.Dispose();  
            cmd.Dispose();  
            con.Close();  

            products.lstExcel = new List<Excel1>();  

            foreach (DataRow dr in dt.Rows)  
            {  
                products.lstExcel.Add(new Excel1  
                {  
                    FileN = dr["FileN"].ToString(),  
                    FilePath = dr["FilePath"].ToString()  
                });  
            }  

        }  
        catch (Exception ex)  
        {  
            adapter.Dispose();  
            cmd.Dispose();  
            con.Close();  
        }  

        if (products == null || products.lstExcel == null || products.lstExcel.Count == 0)  
        {  
            products = new Excel1();  
            products.lstExcel = new List<Excel1>();  
        }  

        return products;  
    }  
}  
Developer technologies ASP.NET Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-11-30T08:35:23.883+00:00

    Hi @JUAN MIGUEL C. NIETO ,
    I tested your controller code and it works fine. Based on your current information, it is not clear where your problem is.
    I wrote a working example based on your current code, you can check it yourself, where is the problem.
    Model

     public class Excel1  
        {         
            public int ID { get; set; }  
            public string FileN { get; set; }  
            public string FilePath { get; set; }  
            public List<Excel1> lstExcel { get; set; }  
      
        }  
    

    Data.cshtml

    @model WebApplication5.Models.Excel1  
    <h2>Data</h2>  
    @foreach (var products in Model.lstExcel)  
    {  
    <h3><u>@products.FileN</u></h3>  
    }  
    

    Controller

    public ActionResult Data()  
            {  
                Excel1 products = GetProducts();  
                ViewBag.Message = "";  
                return View(products);  
            }  
            [HttpPost]  
            public ActionResult Data(Excel1 obj)  
      
            {  
                Excel1 products = GetProducts();  
                return View(products);  
            }  
    

    265617-image.png
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. JUAN MIGUEL C. NIETO 61 Reputation points
    2022-11-29T14:02:45.987+00:00

    265246-image.png

    265198-image.png


  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-11-29T17:19:03.33+00:00

    the error says Model is null, meaning the controller passed a null model to the view. debug the controller that calls this 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.