0

Let's say I want to cascade 2 dropdown list on the selection of the first dropdown value and then store both the values in the database. Everything is working fine. During onclick of the submit button it returns me both the value of the dropdown item which I'm able to store in the database but then it gives me an error saying that "There is no ViewData item of type 'IEnumerable' that has the key 'Request_ID'".

Below is my given code

Model

public class NewTicket

{
 public int? Category_ID { get; set; }
 public int? Request_ID { get; set; }

  public List<SelectListItem> categories { get; set; }
  public List<SelectListItem> request { get; set; }
}

Class for SQLconnection and DataTable

 public class DAL
{
    DataSet ds;
    SqlDataAdapter da;

    public static SqlConnection connect()
    {
        //Reading the connection string from web.config    
        string Name = ConfigurationManager.ConnectionStrings["HelpDeskDBContext"].ConnectionString;
        //Passing the string in sqlconnection.    
        SqlConnection con = new SqlConnection(Name);
        //Check wheather the connection is close or not if open close it else open it    
        if (con.State == ConnectionState.Open)
        {
            con.Close();

        }
        else
        {

            con.Open();
        }
        return con;

    }

    public DataTable MyMethod(string Query)
    {
        ds = new DataSet();
        DataTable dt = new DataTable();
        da = new SqlDataAdapter(Query, DAL.connect());

        da.Fill(dt);
        List<SelectListItem> list = new List<SelectListItem>();
        return dt;

    }
}

User Controller with JSON result

 public class UserController : Controller
{

   DAL objdal = new DAL();

    public ActionResult NewTickets()
    {
        NewTicket model = new NewTicket();

         string requeststring = "SELECT Request_ID, Request_Type FROM REQUEST_TYPE WHERE Request_ID != 2";
         DataSet ds = new DataSet();
         List<string> li = new List<string>();
         DataTable dt = new DataTable();
         dt = objdal.MyMethod(requeststring);
         List<SelectListItem> list = new List<SelectListItem>();
         foreach (DataRow row in dt.Rows)
         {

             list.Add(new SelectListItem { Text = Convert.ToString(row.ItemArray[1]), Value = Convert.ToString(row.ItemArray[0]) });

         }



        ViewBag.requestlist = list;

        return View();
    }

    [HttpPost]
    public ActionResult NewTickets(NewTicket tic)
    {
        AddDetails(tic);
        return View();
    }

    [HttpPost]
    public JsonResult getstate(int id)
    {


        string requeststring = "SELECT DISTINCT Category_ID, Category_Name FROM CATEGORY WHERE Request_ID != 2 AND Request_ID = '" + id + "'";


        DataTable dt = new DataTable();
        dt = objdal.MyMethod(requeststring);
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem { Text = "--Select Request--", Value = "0" });
        foreach (DataRow row in dt.Rows)
        {

            list.Add(new SelectListItem { Text = Convert.ToString(row.ItemArray[1]), Value = Convert.ToString(row.ItemArray[0]) });

        }


        return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));


    }

    private SqlConnection con;

    //To Handle connection related activities
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["HelpDeskDBContext"].ToString();
        con = new SqlConnection(constr);

    }

    //To add Records into database 
    private void AddDetails(NewTicket tic)
    {
        string requeststring = "SELECT Request_ID, Request_Type FROM REQUEST_TYPE WHERE Request_ID != 2";
        DataSet ds = new DataSet();
        List<string> li = new List<string>();
        DataTable dt = new DataTable();
        dt = objdal.MyMethod(requeststring);
        List<SelectListItem> list = new List<SelectListItem>();
        foreach (DataRow row in dt.Rows)
        {

            list.Add(new SelectListItem { Text = Convert.ToString(row.ItemArray[1]), Value = Convert.ToString(row.ItemArray[0]) });

        }   

        connection();
        SqlCommand com = new SqlCommand("Insert_DropDown", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@RequestID", tic.Request_ID);
        com.Parameters.AddWithValue("@CategoryID", tic.Category_ID);
        con.Open();
        com.ExecuteNonQuery();
        con.Close();

    }

}

View

<div class="col-md-12">
  <ul class="nav navbar-nav navbar-right">
    <li class="dropdown">
      <label><b> اختر نوع الطلب </b></label>


      @Html.DropDownListFor(m => m.Request_ID, ViewBag.requestlist as List<SelectListItem>, "--Select Request--", new
      {
        size = "-5",
        style = "width: 100%"
      })


    </li>
    <li>
      <label><b> اختر نوع الطلب </b></label>


      @Html.DropDownListFor(m => m.Category_ID, new SelectList(string.Empty, "Value", "Text"), "--Select Category--", new
      {
        size = "-5",
        style = "width: 100%"
      })

    </li>
  </ul>
</div>

Jquery for POST cascade dropdown and POST Inserting dropdown values in database

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">


$(document).ready(function () {

    $("#Request_ID").change(function () {
        $("#Category_ID").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("getstate")',

            dataType: 'json',

            data: { id: $("#Request_ID").val() },


            success: function (category) {


                $.each(category, function (i, category) {
                    $("#Category_ID").append('<option value="' + category.Value + '">' +
                         category.Text + '</option>');

                });
            },
            error: function (ex) {
                alert('Failed to retrieve request category.' + ex);
            }
        });
        return false;
    })
});

    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "User/NewTickets", // Controller/View 
                data: { //Passing data
                    Request_ID: $("#Request_ID").val(), //Reading dropdown values using Jquery 
                    Category_ID: $("#Category_ID").val()
                }

            });

        });
    });

</script>   
tereško
  • 58,060
  • 25
  • 98
  • 150
  • Because in the POST method you return the view but did not populate the SelectLists as you did in the GET method. –  Feb 01 '18 at 07:07
  • But there are numerous other issues with your code that will cause it to fail. Study the code in [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) to understand how to do this correctly –  Feb 01 '18 at 07:09
  • Can you underline what are the other issues that can cause it to fail? – Hussain Abdul Majeed Feb 01 '18 at 07:12
  • There are too many to go into, but for example, when your user selects items from both dropdowns, submits, and `ModelState` is invalid (which is the only time you ever use `return View()`, then the 2nd dropdown is empty - the value that the user entered is gone –  Feb 01 '18 at 07:14
  • Aha. I see. Thanks a lot for the help. – Hussain Abdul Majeed Feb 01 '18 at 07:20

0 Answers0