是否可以根据同一表单上输入字段的值刷新@Html.DropDownList
?
例如,我有一个字段@Html.TextBoxFor(m => m.CustomerFunds)
,输入50之类的值,一旦用户退出字段,例如TAB,就会启动一个函数来填充DropDownList。
HomeController.cs
public ViewResult Index()
{
var productList = new List<WebApplication1.Product>
{
new WebApplication1.Product{ProductName = "Please select a Product", ProductId = 0}
};
productList.AddRange(_repository.GetAllProducts());
ViewBag.ProductList = new SelectList(productList, "ProductId", "ProductName", null);
return View();
}
public SelectList GetProducts(int customerFunds)
{
var productList = new List<WebApplication1.Product>
{
new WebApplication1.Product {ProductName = "Please select a Product", ProductId = 0}
};
productList.AddRange(_repository.GetProducts(customerFunds));
return new SelectList(productList, "ProductId", "ProductName", null);
}
Index.cshtml
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { role = "form" }))
{
@Html.TextBoxFor(m => m.CustomerFunds)
@Html.DropDownList("ProductId", ViewBag.ProductList as SelectList)
}
更新
我已将GetProducts函数更改为:
public ActionResult GetProducts(decimal customerFunds)
{
var products = _repository.GetProducts(customerFunds).Select(p => new { p.ProductId, p.ProductName }).OrderBy(p => p.ProductName);
return Json(products, JsonRequestBehavior.AllowGet);
}
Index.cshtml现在如下:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { role = "form" }))
{
@Html.TextBoxFor(m => m.CustomerFunds)
<select id="ProductId">
<option value="0">Please select a Product</option>
</select>
}
<script type="text/javascript">
$(document).ready(function () {
$('#ProductId').hide();
$('#CustomerFunds').blur(function () {
var customerFunds = $(this).val();
if (propertyValue.length > 0) {
$.getJSON('/Home/GetProducts', { customerFunds: customerFunds }, function (data) {
$('#ProductId').show();
$('#ProductId option').remove();
$('#ProductId').append('<option value="0">Please select a Product</option');
for (var i = 0; i < data.length; i++) {
$('#ProductId').append('<option value="' + data[i].ProductID + '">' + data[i].ProductName + '</option');
}
}).fail(function () {
debugger;
alert('Error getting Products');
});
}
else {
$('#ProductId option').remove();
$('#ProductId').append('<option value="0">Please select a Product</option');
}
});
});
</script>
将数据输入CustomerFunds
并按下TAB键后,将显示下拉列表并填充。
但是,在填充下拉列表时查看页面的源HTML时,实际的选择列表仅显示:
<select id="ProductId">
<option value="0">Please select a Product</option>
</select>
尽管页面实际呈现了列表,但下拉列表的选定值未传递到模型中,因此模型验证失败,我不明白为什么。
更新
感谢markpsmith,ProductId
的选择应该如下:
<select id="ProductId" name="ProductId">
<option value="0">Please select a Product</option>
</select>