Search results

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

21 Oct 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 e-grid-column tag helper. 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.

tagHelper
edit-template-foreign.cs
Copied to clipboard
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Customer ID" type="string" width="120" foreignKeyValue='LastName' dataSource="ViewBag.ForeignData" edit="@(new {create="create", read="read", destroy="destroy", write="write"})"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150" editType='dropdownedit'></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>

    var autoComplete;
    var employeeData = @Json.Serialize(ViewBag.ForeignData);

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

    function read () { // return edited value to update data source
        let value = new ej.data.DataManager(employeeData).executeLocal(new ej.data.Query().where('LastName', 'equal', autoComplete.value));
        return value.length && value[0]['EmployeeID']; // to convert foreign key value to local value.
    }

    function destroy () { // to destroy the custom component.
        autoComplete.destroy();
    }

    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]
        });
        autoComplete.appendTo(args.element);
    }

</script>
Copied to clipboard
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    ViewBag.ForeignData = EmployeeDetails.GetAllRecords();
    return View();
}