级联下拉列表并使用MVC,Ajax在数据库中存储值

时间:2018-02-01 06:46:13

标签: jquery asp.net-mvc

假设我想在选择第一个下拉列值时级联2下拉列表,然后将这两个值存储在数据库中。一切都很好。在点击提交按钮的过程中,它返回了我能够存储在数据库中的下拉项的值,但是它给了我一个错误,说明"没有类型&#的ViewData项39; IEnumerable的'具有密钥' Request_ID'"。

以下是我给出的代码

模型

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; }
}

SQL连接类和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;

    }
}

具有JSON结果的用户控制器

 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();

    }

}

查看

<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>

用于POST级联下拉列表和POST插入数据库中的下拉值的Jquery

<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>   

0 个答案:

没有答案