Kendo UI Grid - 显示外键值而不是ID

时间:2013-11-12 08:20:32

标签: javascript asp.net-mvc kendo-ui

网格使用包含外键值的下拉列表。现在,我可以选择一个项目,但我只能在网格中看到相应的项目ID而不是它的名称。

我尝试按照this post中的步骤操作,但我看到的只是网格行中的'undefined'。有什么想法吗?

顺便说一句,我正在使用Kendo UI的开源版本,其中所有内容都使用JavaScript。

3 个答案:

答案 0 :(得分:0)

您需要使用模板。

在你的模型中有另一个与名称相关的字段(你需要在编辑时将其设置为正确的值),然后使用像     "#=#名称

首先按照以下方式创建列:

columns.Bound(x => x.ForeignKey).ClientTemplate("#=Name#");

然后在控制器的Update方法中,将视图模型上的Name属性设置为您想要的属性。

viewModel.Name = GetName(viewModel.ForeignKey);
return this.Json(new[] { viewModel }.ToDataSourceResult(request, this.ModelState));

编辑2: 要在javascript模式下构建网格,您需要像这样定义列:

{ field: "ForeignKey", title: "Foreign Key", template: '#=Name#', editor: myEditor}

然后像这样定义你的编辑器:

function myEditor(container, options) {
    $('<input required data-text-field="ForeignKeyName" data-value-field="ForeignKey" data-bind="value:' + options.field + '"/>')
        .appendTo(container)
        .kendoDropDownList({
            autoBind: false,
            dataSource: myDataSource
        });
}

您可能仍需要设置该值,但是,如果您想在服务器端执行此操作,则可以使用上面提到的方法,如果您要执行此客户端,则需要处理网格保存事件并在那里设置数据源中的值。

希望这会有所帮助。

答案 1 :(得分:0)

我最终要求Telerik提供支持,工作解决方案显示在JS Bin

答案 2 :(得分:0)

这是MVC版本,但在这里,您不需要模板。参见:

http://decisivedata.net/kendo-ui-grid-and-entity-framework-code-first-foreign-key-fields/

假设您要获取产品名称,而不是在订单表上使用ProductID。您可以使用以下列:

columns.ForeignKey(c => c.ProductID, (IEnumerable)ViewData["Products"], dataFieldText: "ProductName", dataFieldValue: "ProductID");

确保您的模型在Orders模型中具有外键:

 [ForeignKey("ProductID")]
 public Product FKProduct { get; set; }  

您更新控制器:

public class HomeController : Controller {        
    private NorthwindRepository northwindRepository = new NorthwindRepository();
    public ActionResult Index()
    {
        PopulateProducts();         
        return View(northwindRepository.OrderDetails);     
    }
    private void PopulateProducts()     
    {         
        ViewData["Products"] = northwindRepository.Products;     
    }
}