我有一个View页面,其中包含从自定义构造函数类填充的值的下拉列表。
DDL中填充了从自定义项列表中创建的SelectList,如下所示:
public class CustomerType
{
public int Id { get; set; }
public string Name { get; set; }
public string ValidationRule { get; set; }
}
在我的视图中,我将其设置为: @ Html.DropDownListFor(model => model.Id,(IEnumerable)Model.SelectListOfCustomItems,“Please select ...”)
我想要尝试做的是为所选的每个项目显示ValidationRule属性,并在Label中显示。
我想我必须使用JavaScript来做到这一点,但我不确定如何实际获得ValidationRule属性?我可能使用类似于下面的代码获取所选项目,但我看不到如何向下钻取以获取其他数据?
var dropDown = document.getElementById("MyDropDownListName");
dropDown.onchange = function () { DisplayValidationRule(this); };
function DisplayValidationRule(ddl)
{
document.getElementById('lblRule').textContent = [Unknown]
}
我缺少的是我标记它[未知]的地方,因为我没有俱乐部如何得到这个。我想的可能是ddl.items[ddl.selectedItem].value['ValidationRule']
,但这对我不起作用。
答案 0 :(得分:1)
有很多方法可以实现它。一种方法是生成一组隐藏的输入字段,如id =“_ CustomerType_id_xxx”,其值为“ValidationRule”,然后根据选择结果获取值。另一种方法是发送ajax请求以获取规则。但我认为这不是一个好方法。
好的,下面是我的完整代码,它传递给MVC4。
HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
IList<CustomerType> customerTypes = new List<CustomerType>();
customerTypes.Add(new CustomerType { Id = 1, Name = "Customer Type 1", ValidationRule = "Rule 1" });
customerTypes.Add(new CustomerType { Id = 2, Name = "Customer Type 2", ValidationRule = "Rule 2" });
customerTypes.Add(new CustomerType { Id = 3, Name = "Customer Type 3", ValidationRule = "Rule 3" });
IEnumerable<SelectListItem> selectList =
from c in customerTypes
select new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
};
return View(new CustomerVO { SelectListOfCustomItems = selectList, CustomerTypes = customerTypes });
}
}
Index.cshtml
@model MvcApplication1.Models.CustomerVO
@Html.DropDownListFor(model => model.CustomerTypeId, Model.SelectListOfCustomItems, "Please select...")
@foreach (var customerType in Model.CustomerTypes)
{
<input type="hidden" id="_customerType_@customerType.Id" value="@customerType.ValidationRule" />
}
<label id="lblRule"></label>
@section scripts
{
<script>
$(document).ready(function () {
var dropDown = document.getElementById("CustomerTypeId");
dropDown.onchange = function () { DisplayValidationRule(this); };
function DisplayValidationRule(ddl)
{
document.getElementById('lblRule').textContent = $("#_customerType_" + ddl.value).val();
}
});
</script>
}