这是视图部分:
在此视图中,从数据库中检索“产品名称”下拉列表,iam要做的是在选择产品名称之后,必须在价格文本框中填充价格。产品名称,价格和其他列已经存储在数据库中。
<div class="form-group">
<div class="row">
<label class="col-sm-8 control-label no-padding-right">Product Name</label>
</div>
<div class="row">
<div class="col-sm-8">
@Html.DropDownList("Product_Name", (SelectList)ViewBag.Values, "Please select", new { @id = "populate", @class = "SelectCtrlGHN", onchange = "return get_sbu(this)" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-sm-8 control-label no-padding-right">Price</label>
</div>
<div class="row">
<div class="col-sm-8">
<input type="text" name="Price" class="col-xl-4 col-sm-8" id="pric" />
</div>
</div>
</div>
获取价格的脚本:
在这里,我已编写脚本来根据视图中相应的下拉列表选择检索价格。
<script type="text/javascript">
$(document).ready(function() {
$('#populate').change(function() {
var str = this.options[this.selectedIndex].value;
var st = null;
$.ajax('@Url.Action("GetProductData", "Userrolereq")', {
type: 'POST',
dataType: 'json',
data: { 'productID': str },{'amt':st},
success: function(data, status, jqXHR) {
if ("success" === status) {
document.getElementById('#populate').value = data.productID;
document.getElementById('#pric').value = data.amt;
}
if ("productCode" != null) {
document.getElementById('#pric').value = data.amt;
}else {
alert('This Product ID is not valid. Try again!');
}
}
});
});
});
</script>
这是控制器:
从数据库iam的DM_Userreq表中尝试从下拉选择中检索价格。
public ActionResult GetProductData(string productID)
{
string sa = "";
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
StringBuilder sb = new StringBuilder();
using (cn)
{
cn.Open();
string que = string.Format("Select Price From DM_Userreq Where Product_Name = '{0}'", productID);
SqlCommand cm = new SqlCommand(que, cn);
SqlDataReader rd = cm.ExecuteReader();
while (rd.Read())
{
sb.Append(rd["Price"].ToString() + "</br>");
return Json(new { success = true, productCode = sb.Append(rd["Price"].ToString() + "</br>") });
}
sa = sb.ToString();
cn.Close();
}
return Json(new { success = false });
}