ASP.Net MVC Error: Object reference not set to an instance of an object after form submit

Last Reply 5 months ago By dharmendr

Posted 5 months ago

hi

I put dropdownlist in View to insert selected Item's Id into database below are codes:

  public partial class Reseller
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int OstanId { get; set; }
        public Nullable<int> CityId { get; set; }
        public string Address { get; set; }
        public string OstanName { get; set; }
        public string CityName { get; set; }    
        public virtual City City { get; set; }
        public virtual Ostan Ostan { get; set; }
    }

view model:

    public class AddResellerViewModel
    {
        public Reseller Reseller { get; set; }
        public List<SelectListItem> Ostans { get; set; }
        public string OstanName { get; set; }

    }

controller:

        [HttpGet]
        public ActionResult AddReseller()
        {
            var model = new AddResellerViewModel();
            model.Ostans = PopulateOstan();
            return View(model);
        }

     [HttpPost]
        public ActionResult AddReseller(Reseller reseller)
        {
            SqlConnection constr = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Constring"].ConnectionString);

            using (SqlCommand cmd = new SqlCommand("InsertReseller", constr))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = constr;
                constr.Open();
                cmd.Parameters.AddWithValue("@Name", reseller.Name);
                cmd.Parameters.AddWithValue("@Address", reseller.Address);
                cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);
                cmd.ExecuteNonQuery();
                constr.Close();

            }
            return View();
        }

View:

@model MvcInternetShop.ViewModels.Test.AddResellerViewModel
@using (Html.BeginForm("AddReseller", "Test", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div class="group">
        @Html.LabelFor(model => model.Reseller.OstanId, new { @class = "label" })
    <div class="controls"> 
        @Html.DropDownListFor(model => model.Reseller.OstanId, new SelectList((List<SelectListItem>)Model.Ostans, "Value", "Text"), "please Select")
        @Html.ValidationMessageFor(model => model.Reseller.OstanId)
    </div>
</div>

ERROR:

Additional information: Object reference not set to an instance of an object.

but I put breakpoint on 

[HttpPost] public ActionResult AddReseller(Reseller reseller) {

and I checked this line:

 cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);

and it has selected Item Id value.

Posted 5 months ago

Hi nedash,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Model

public class AddResellerViewModel
{
    public Reseller Reseller { get; set; }
    public List<SelectListItem> Ostans { get; set; }
    public string OstanName { get; set; }
}

public class Reseller
{
    public int OstanId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        var model = new AddResellerViewModel();
        model.Ostans = PopulateOstan();
        return View(model);
    }

    [HttpPost]
    public ActionResult AddReseller(Reseller reseller)
    {
        SqlConnection constr = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Constring"].ConnectionString);
        using (SqlCommand cmd = new SqlCommand("InsertReseller", constr))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = constr;
            constr.Open();
            cmd.Parameters.AddWithValue("@Name", reseller.Name);
            cmd.Parameters.AddWithValue("@Address", reseller.Address);
            cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);
            cmd.ExecuteNonQuery();
            constr.Close();
        }

        return RedirectToAction("Index");
    }

    private static List<SelectListItem> PopulateOstan()
    {
        SqlConnection constr = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Constring"].ConnectionString);
        List<SelectListItem> items = new List<SelectListItem>();
        using (SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName + ' ' + LastName Name FROM Employees", constr))
        {
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = constr;
            constr.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    items.Add(new SelectListItem
                    {
                        Text = sdr["Name"].ToString(),
                        Value = sdr["EmployeeID"].ToString()
                    });
                }
                constr.Close();
            }
            return items;
        }
    }
}

View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<_DropDownList_Selected_Insert_MVC.Models.AddResellerViewModel>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
</head>
<body>
    <% using (Html.BeginForm("AddReseller", "Home", FormMethod.Post))
       {%>
    <table>
        <tr>
            <td>Ostan</td>
            <td><%:Html.DropDownListFor(model => model.Reseller.OstanId, new SelectList((List<SelectListItem>)Model.Ostans, "Value", "Text"), "please Select")%></td>
        </tr>
        <tr>
            <td>Name</td>
            <td><%:Html.TextBoxFor(model => model.Reseller.Name)%></td>
        </tr>
        <tr>
            <td>Address</td>
            <td><%:Html.TextBoxFor(model => model.Reseller.Address)%></td>
        </tr>
    </table>
    <br />
    <input type="submit" value="Save" />
    <% } %>
</body>
</html>

Screenshots

The form Data

The values in Controller


Posted 5 months ago

Hi nedash,

In your GET action method, you are loading data for the DropDownList and sending to the view.

But in your HttpPost action method, When you are returning the same view. But you are not passing any model / viewmodel to that which has data for your DropDownList.

Your razor view is trying to use the Ostans collection to render the DropDownList, but since Model is NULL you are getting this error.

What you should do is before returning the view, reload the Ostans property values again.

[HttpPost]
public ActionResult AddReseller(Reseller reseller)
{
    SqlConnection constr = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Constring"].ConnectionString);
    using (SqlCommand cmd = new SqlCommand("InsertReseller", constr))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = constr;
        constr.Open();
        cmd.Parameters.AddWithValue("@Name", reseller.Name);
        cmd.Parameters.AddWithValue("@Address", reseller.Address);
        cmd.Parameters.AddWithValue("@Ostanid", reseller.OstanId);
        cmd.ExecuteNonQuery();
        constr.Close();
    }

    var model = new AddResellerViewModel();
    model.Ostans = PopulateOstan();
    return View(model);
}

Or simply use RedirectToAction method which i provided earlier in the sample.