【发布时间】:2017-03-28 12:14:38
【问题描述】:
在我的页面中,我有一个部门下拉列表,用户从中选择任何部门,在选择这个部门时,我调用更改事件,在这种情况下,我编写 jquery ajax 代码并在 url 中调用控制器 getcustomers 方法它从数据库视图中查询,但这个 ajax 方法不起作用,我也在控制台调试器模式下看到它,我想填充客户下拉列表所需的帮助。
注意:我只想从此数据库视图中获取客户。
Plz see the image of database view here
<script type="text/javascript">
//Dropdownlist Selectedchange event
function DivisionChanged(item) {
//$("#dvn_code").change(function () {$('#dvn_code')
var select_division = $(item).val();
$("#customers").empty();
debugger;
$.ajax({
url: '@Url.Action("GetCustomers")',
type: 'POST',
@*url: '@Url.Action("GetStates")'*@ // we are calling json method
dataType: 'json',
data: { id: $(this).val() },
success: function (data) {
customers.append($('<option/>', { value: -1, text: 'Select customers' }));
$(data).each(function (index, item) {
customers.append($('<option/>', { value: item.id, text: item }));
});
}
});
return false;
}
</script>
///// 控制器代码
public JsonResult GetCustomers(int id)
{
string cs = ConfigurationManager.ConnectionStrings["DBContext"].ConnectionString;
List<V_CustomerForDropDown> customers = new List<V_CustomerForDropDown>();
String query = "SELECT cst_Name FROM PT.V_CustomerForDropDown where dvn_code==id";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(query, con);
//cmd.CommandType = CommandType.TableDirect;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
V_CustomerForDropDown c = new V_CustomerForDropDown();
c.cst_Name = rdr["cst_Name"].ToString();
customers.Add(c);
}
// con.Close();
return this.Json(customers);
}
}
更新(现在这是问题): 我以 json 格式传递数据以从控制器查看,它也传递数据,但查看如何在下拉列表中填充它
// 控制器
[HttpPost]
public ActionResult GetCustomers(string id)
{
var customers = (from a in db.V_CustomerForDropDown.Where(c => c.dvn_code == id) select new { a.cst_Name, a.cst_Code }).ToList();
return Json(customers, JsonRequestBehavior.AllowGet);
}
//index.chtml
<div class="col-md-4">
<select class="form-control selectpicker" id="customers" multiple title="Multiple Select" data-live-search="true" data-menu-style="dropdown-blue">
</select>
// javascript代码
<script type="text/javascript">
function DivisionChanged(item) {
var select_division = $(item).val();
$.ajax({
url: '@Url.Action("GetCustomers")',// we are calling json method
type: 'POST',
dataType: 'json',
data: { id: select_division },
success: function (customers) {
debugger;
$.each(customers, function (i, cust) {
$("#customers").append('<option value>' + cust.cst_Name + '</option>');
});
}
});
return false;
}
</script>
【问题讨论】:
-
字符串查询 = String.Format("SELECT cst_Name FROM PT.V_CustomerForDropDown where dvn_code=={0}",id)
-
not working 没用。什么不工作?你得到什么错误?
-
@StephenMuecke 我以 json 格式传递数据以从控制器查看,它也传递数据,但要查看如何在下拉列表中填充它,请参阅我更新的问题
标签: javascript jquery ajax asp.net-mvc sql-server-2008-r2