Tuesday, September 23, 2014

Nullable Foreign Keys

Kendo grid doesn't support nullable foreign keys, to allow a drop down list to appear in place of a nullable foreign key:

1.  Make sure you have the Views/Shared/GridForeignKey.cshtml template from Kendo
2.  Decorate your model field like this
[UIHint("GridForeignKey")]
[DisplayName("Contact Type")]
3.   Pass ViewData from the controller and code up the key:
c.ForeignKey( k => k.fk_ContactTypeID,(IEnumerable)ViewData["ContactTypeList"],"pk_contact_TypeID", "contactType1").EditorTemplateName("ContactTypeTemplate").Title("Contact Type").Width("180px");
.Events(e => { e.Edit("editmode"); e.Save("onSave"); })


<script>
function onSave(e) {
        if (!e.model.fk_ContactTypeID) {
            //change the model value
            e.model.fk_ContactTypeID = 0;
            //get the currently selected value from the DDL
            var currentlySelectedValue = $(e.container.find('[data-role=dropdownlist]')[0]).data().kendoDropDownList.value();
            //set the value to the model
            e.model.set('fk_ContactTypeID', currentlySelectedValue);
        }
    }
</script>

No comments:

Post a Comment