0

I am trying use dropdown to insert values to Database. Values from dropdown can insert into database all data completed. But it still alert error in View.

Value cannot be null

 @Html.DropDownListFor(Model => Model.JCY_SEC, new SelectList(ViewBag.Names as System.Collections.IEnumerable, "SECID", "SecTH"), "Select a Section")  

This is my controller

[HttpGet]
public ActionResult EmployeeView()
{
    ViewBag.Names = db.HRset_Section.ToList();
    return View();
}

and this is my insert method

public ActionResult EmployeeView(EMPJCYMODEL customer, FormCollection collection)
{
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        string query = "INSERT INTO HR_EMPLOYEE(JCY_EMPNO, JCY_EMP_NAME,JCY_EMP_SUR,st_date,JCY_SEC) VALUES(@JCY_EMPNO, @JCY_EMP_NAME,@JCY_EMP_SUR,@st_date,@JCY_SEC)";
        query += " SELECT SCOPE_IDENTITY()";
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Connection = con;
            con.Open();
            cmd.Parameters.AddWithValue("@JCY_EMPNO", customer.JCY_EMPNO);
            cmd.Parameters.AddWithValue("@JCY_EMP_NAME", customer.JCY_EMP_NAME);
            cmd.Parameters.AddWithValue("@JCY_EMP_SUR", customer.JCY_EMP_SUR);
            cmd.Parameters.AddWithValue("@st_date", customer.st_date);
            cmd.Parameters.AddWithValue("@JCY_SEC", customer.JCY_SEC);
            customer.JCY_EMPNO = cmd.ExecuteScalar().ToString();
            con.Close();
        }
    }
    return View(customer);
}
  • Your `ViewBag.Names` may returns null. Try declaring `ViewBag.Names = new SelectList(...)` from controller then using `ViewBag.Names as SelectList` instead of passing `IEnumerable` to view. – Tetsuya Yamamoto Apr 04 '17 at 03:13
  • Because you return the view in the POST method and do not reset the `ViewBag.Names` property. –  Apr 04 '17 at 03:15
  • can u guys revise my code? – Kane Smith Sillapasit Apr 04 '17 at 03:18
  • Just add `ViewBag.Names = db.HRset_Section.ToList();` in the POST method before your `return View(customer);` (and delete the pointless `FormCollection collection` in your method signature). But why are you returning the view anyway. –  Apr 04 '17 at 03:19
  • @StephenMuecke EmployeeView this view for create new i new for MVC dont i think have always 2 method 1 show 1 process – Kane Smith Sillapasit Apr 04 '17 at 03:24
  • @StephenMuecke thank you u save me for 3 days ! i have many about mvc to know – Kane Smith Sillapasit Apr 04 '17 at 03:27

0 Answers0