A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.telerik.com/aspnet-mvc/html-helpers/data-management/grid/columns/foreignkey-column below:

ASP.NET MVC Data Management Grid Columns ForeignKey Column

New to Telerik UI for ASP.NET MVC? Start a free 30-day trial ForeignKey Column

The ForeignKey column functionality of the Telerik UI Grid component for ASP.NET MVC is primarily used for matching the value of a bound property to a desired text field from a collection external to the Grid. It follows the convention of the SQL ForeignKey functionality that links two tables based on a foreign key.

ForeignKey Coulmn Data Binding

You can supply the foreign values for the columns of the Grid using the following approaches:

Binding to Local Data

To implement a ForeignKey column in the Grid that binds to a local data collection of items, pass a valid IEnumerable collection to the ForeignKey() column configuration.

The example below shows the following ForeignKey column declaration:

columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName").Title("Category").Width(200);
public class GridController : Controller
{
    public ActionResult Index()
    {
        ViewData["categories"] = GetCategories();
        return View();
    }

    private IEnumerable<CategoryViewModel> GetCategories()
    {
        var dataContext = new DemoDBContext();
        var categories = dataContext.Categories
        .Select(c => new CategoryViewModel {
            CategoryID = c.CategoryID,
            CategoryName = c.CategoryName
        })
        .OrderBy(e => e.CategoryName);
    }
}
public class CategoryViewModel{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

For a live example, visit the ForeignKey Column Demo of the Grid.

Binding to Remote Data

To bind the Grid column to a remote collection of items, specify a URL to the remote endpoint that returns the data instead of a static collection. It is mandatory to supply the dataFieldValue and dataFieldText parameters to ensure the column values will bind to the correct foreign key value.

The example below shows the following ForeignKey() column configuration:

    columns.ForeignKey(p => p.CategoryID, ds => ds.Read(r => r.Action("Categories", "Grid")), "CategoryID", "CategoryName").Title("Category").Width(200);
public class GridController : Controller
{
    public JsonResult Categories()
    {
        var dataContext = new DemoDBContext();
        var categories = dataContext.Categories
        .Select(c => new CategoryViewModel
        {
            CategoryID = c.CategoryID,
            CategoryName = c.CategoryName
        })
        .OrderBy(e => e.CategoryName);

        return Json(categories, JsonRequestBehavior.AllowGet);
    }
}
    public class CategoryViewModel{
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }

For a live example, visit the ForeignKey Column Binding Demo of the Grid.

ForeignKey Column Editor

The ForeignKey column supports a built-in DropDownList editor and a custom editor.

Default Editor

By design, when the Grid is editable and contains a ForeignKey column, it builds an internal DropDownList editor template GridForeignKey located in the ~/Views/Shared/EditorTemplates/ folder.

@model object

@(
 Html.Kendo().DropDownListFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
    .HtmlAttributes(new { title = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("")})
)

To enable the default GridForeignKey editor when the Grid is set up for Popup editing, decorate the model property bound in the ForeignKey column with the UIHint data attribute and specify the name of the view that contains the default editor (GridForeignKey):

public class ProductViewModel
{
    public int ProductID { get; set; }
    [UIHint("GridForeignKey")]
    public int CategoryID { get; set; }
}
@model object

@(
 Html.Kendo().DropDownListFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
    .HtmlAttributes(new { title = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("")})
)
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName").Title("Category").Width(200);

When the Grid is set up for Inline or InCell editing, the default ForeignKey column editor activates automatically when the row or cell enters edit mode.

Custom Editor

To use a custom editor for the ForeignKey column, use the ForeignKey() overload and set its useServerEditor argument to true to indicate that a custom editor must be used.

To use a custom editor for the ForeignKey column in HtmlHelper Grid, it is required to configure the column for remote data-binding.

The following example shows how to create a custom editor for a ForeignKey column in an editable HtmlHelper Grid:

  1. Define a ForeignKey column in the Grid by using the remote data-binding approach and set the last argument to true:

    columns.ForeignKey(p => p.ProductId, ds => ds.Read(r => r.Action("GetProducts", "Home")), "ProductId", "ProductName", true);
  2. Add a view that contains the desired editor in the ~/Views/Shared/EditorTemplates/ folder:

    @model object
    
    @(Html.Kendo().DropDownListFor(m => m)
        .Filter("contains")
        .DataTextField("ProductName")
        .DataValueField("ProductId")
        .DataSource(d => d.Read(r => r.Action("GetProducts", "Home")).ServerFiltering(false))
    )
    public JsonResult GetProducts()
    {
        var northwind = new DemoDBContext();
        var products = northwind.Products.Select(product => new ProductViewModel
        {
            ProductId = product.ProductId,
            ProductName = product.ProductName
        });
        return Json(products, JsonRequestBehavior.AllowGet);
    }
    public class ProductViewModel
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }
  3. If the Grid is set up for InCell or Popup editing, decorate the ProductId property with the UIHint data attribute and specify the name of the view that contains the custom editor (CustomFKeyEditor). If the Grid is configured for Inline editing, use the EditorTemplateName() option to specify the custom editor.

    public class GridViewModel
    {
        [UIHint("CustomFKeyEditor")]
        public int ProductId { get; set; }
    }
    columns.ForeignKey(p => p.ProductId, ds => ds.Read(r => r.Action("GetProducts", "Home")), "ProductId", "ProductName", true).EditorTemplateName("CustomFKeyEditor");
  4. Specify the default value for the ForeignKey field in the Model() configuration of the DataSource. It will be used when adding a new record to the Grid.

        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model =>
            {
                model.Id(p => p.Id);
                model.Field(p => p.Id).Editable(false);
                model.Field(p => p.ProductId).DefaultValue(1);
            })
            
        )
See Also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4