Search results

Use Edit Template in Foreign Key Column in ASP.NET MVC Grid control

24 Sep 2021 / 1 minute to read

By default, foreign key column uses dropdown component for editing. You can render other than the dropdown by using the Edit property of Column. The following example demonstrates the way of using edit template in foreign column.

In the following example, The Employee Name is a foreign key column and while editing, AutoComplete component is rendered instead of DropDownList.

Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("EmployeeID").HeaderText("Employee Name").Width("150").ForeignKeyValue("FirstName").DataSource(ViewBag.ForeignData).Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Add();

    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropdownedit").Add();

}).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal);}).Render()

    var autoComplete;
    var employeeData = @Html.Raw(Json.Encode(ViewBag.ForeignData));

    function create() { // to create input element
        return document.createElement('input');

    function read () { // return edited value to update data source
       var value = new'FirstName', 'equal', autoComplete.value));
       return value.length && value[0]['EmployeeID']; // to convert foreign key value to local value.

    function destroy () { // to destroy the custom component.

    function write (args) { // to show the value for custom component
       autoComplete = new ej.dropdowns.AutoComplete({
            dataSource: employeeData,
            fields: { value: args.column.foreignKeyValue },
            value: args.foreignKeyData[0][args.column.foreignKeyValue]
Copied to clipboard
public IActionResult Index()
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    ViewBag.ForeignData = EmployeeDetails.GetAllRecords();
    return View();