locked
insert value from dropdownlist RRS feed

  • Question

  • User-265772647 posted

    Hi,

    im trying to insert value from drop down list  into db ,getting exception

    Html:
    @Html.DropDownListFor(model => model.Branchlist, new SelectList(Model.Branchlist, "BranchId", "BranchOffice"), new { @class = "form-control" })//
    reference not set to an instance of an object.'
    System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
    [HttpGet]
    public ActionResult NonAdminUser()
    {
    
    NonAdminUser multi_Dropdownlist = new NonAdminUser
    {
    /Branchlist = GetBranchLists()
    
    };
    return View(multi_Dropdownlist);
    }
    public List<Branch_List> GetBranchLists()
    {
     string mainconn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
    SqlConnection con = new SqlConnection(mainconn);
    string sqlQuery = "select * from Branch";
    con.Open();
    SqlCommand cmd = new SqlCommand(sqlQuery, con);
    SqlDataReader dr = cmd.ExecuteReader();
    List<Branch_List> branches = new List<Branch_List>();
     if(dr.HasRows)
     {
    while (dr.Read ())
    {
    // branches.Add(new Branch_List
    {
     BranchId = Convert.ToInt32(dr["BranchId"]),
     BranchOffice = Convert.ToString(dr["BranchName"])
    });
     }
     }
    con.Close();
    return branches;
    }
    [HttpPost]
    public ActionResult NonAdminUser(NonAdminUser nonAdmin)
    {
    string mainconn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
    SqlConnection con = new SqlConnection(mainconn);
    string sqlQuery = "insert into NonAdminUser values(@BranchOffice)";
    con.Open();
    SqlCommand cmd = new SqlCommand(sqlQuery, con);
    
    cmd.Parameters.AddWithValue("@BranchOffice", nonAdmin.BranchOffice);
    cmd.ExecuteNonQuery();

    Thursday, May 21, 2020 8:59 PM

All replies

  • User475983607 posted

    Please do not make the community guess.  Which line causes the null exception?  Is there a problem populating the drop down list or submitting the HTML form?

    Also, please format your code when posting on the forum.  Use the "Insert/Edit code sample" when sharing code.

    Thursday, May 21, 2020 9:19 PM