我正在使用具有 Razor 语法和最新 Telerik 组件的 Asp.Net。不幸的是,当我单击下拉框时,我什么也看不到,但 VS 调试器显示我执行了 _AjaxLoaiding 方法。我该如何解开这个谜团(即将数据加载到 DropDownList 中)?
这是我的 Controller 的一部分:
public ActionResult _AjaxLoading(string text) {
var product = new Dictionary<string, string>();
product.Add("a","b");
return new JsonResult { Data = new { Text = "Abc", Value = "123", Produtcs = new SelectList(product, "ProductID", "ProductName") } };
}
这是我的 View 的一部分:
@{Html.Telerik().DropDownList()
.Name("documentType").Enable(false)
.HtmlAttributes(new { style = "width:250px;" })
.DataBinding(binding => binding.Ajax().Select("_AjaxLoading", "Applicants"))
.Render();
}
最佳答案
嗯,你做了一件奇怪的事:你传递了一个 Dictionary<string, string>
添加到您的选择列表,并断言 valueField 是“ProductId”,TextField 是“ProductName”。
你的字典没有这样的属性......强类型是好的。
所以你需要一个类产品(或其他)
public class Product {
public int ProductId {get;set;}
public string ProductName {get;set;}
}
并使用它,甚至用于测试目的
public ActionResult _AjaxLoading(string text) {
var products= new List<Product> {
new Product{ProductId = 1, ProductName="b"}
};
return new JsonResult { Data = new { Text = "Abc", Value = "123", Products= new SelectList(products, "ProductID", "ProductName") } };
}
编辑:
顺便说一句,如果您想在 SelectList 中使用“Abc”和“123”,这不是正确的做法,请查看@Gaby 在您之前的帖子中的回答 https://stackoverflow.com/a/10500876/961526
编辑 2:
再试一次
首先,我的一些常用扩展类(我限制了它们,它们以前更通用,但是......无论如何)
public static class ComboExtensions
{
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> enumerable,
Func<T, string> text,
Func<T, int> value)
{
return enumerable.Select(item => new SelectListItem
{
Text = text(item).ToString(),
Value = value(item).ToString(),
}).AsEnumerable();
}
public static IEnumerable<SelectListItem> WithDefaultValue(this IEnumerable<SelectListItem> selectListItems, int defaultValue = 0, string chooseText = "choose")
{
IList<SelectListItem> items = selectListItems.ToList();
items.Insert(0, new SelectListItem {Value = defaultValue.ToString(), Text = chooseText});
然后
public ActionResult _AjaxLoading(string text) {
var products = new List<Product>
{
new Product {ProductId = 1, ProductName = "b"}
}.ToSelectListItem(m => m.ProductName, m => m.ProductId)
.WithDefaultValue(1, "abc");
return new JsonResult { Data = products } };
}
关于c# - 为什么 Telerik DropDown List 在使用 ajax 数据绑定(bind)时没有任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10501994/