This is a migrated thread and some comments may be shown as answers.

Populate new row fields from grid popup

2 Answers 304 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Michael
Top achievements
Rank 1
Michael asked on 11 Sep 2014, 10:24 AM
Hi

I'm having an issue with populating some fields in a Kendo Grid.

I have a page that displays details about a Team. On that page is a Kendo grid that displays a list of members in the current team that is being viewed. The grid has the following columns

Username
FirstName
LastName
EffectiveFromDate
EffectiveToDate

The page can be put into an edit state which allows you to then edit or delete team members in the grid using edit or delete buttons in each row of the grid. There is also top level option to add a new member to the team.

When i click on the new button to add a new member, a popup is displayed. On the popup is an autocomplete list for selecting who is to be added to the team, and two datetime pickers for the effective to and from dates.

When i select a user from the autocomplete, enter the effective to and from dates, and click Ok to close the popup, a new row is added to the grid as expected. But the Username, First Name and Last Name fields are not populated.

I have added hidden fields onto the popup view that are populated on an onUserAutoCompleteChanged event in the AutoComplete view. When i debug i can see these fields are being correctly populated with the correct data when i make a user selection with the autocomplete. The issue is that the data is not being re-bound to the grid when i close the popup.

I added a text field for FirstName to the popup so i could see that it was being populated when i made a selection in the autocomplete, which it definitely is.

If i make a user selection without making any changes to the First Name text field and close the popup, the data is not displayed in the grid although a new row is created. However, if i select a user from the autocomplete to populate the FirstName text field and then alter the text in that field, and then close the popup, the data is displayed in the grid for FirstName.

How do i go about firing whatever is causing the data to bind to the grid when i update the text field without having to update the text field?

TeamPage cshtml
<div class="row">
    <div class="form-group  col-md-6 ">
        @Html.LabelFor(model => model.TeamCode)
        @Html.EditorFor(model => model.TeamCode)
        @Html.ValidationMessageFor(model => model.TeamCode)
    </div>
</div>
<div class="row">
    <div class="form-group  col-md-6 ">
        @Html.LabelFor(model => model.TeamName)
        @Html.EditorFor(model => model.TeamName)
        @Html.ValidationMessageFor(model => model.TeamName)
    </div>
</div>
<div class="row">
    <div class="form-group  col-md-12 ">
        @Html.LabelFor(model => model.TeamDesc)
        @Html.EditorFor(model => model.TeamDesc)
        @Html.ValidationMessageFor(model => model.TeamDesc)
    </div>
</div>
<div class="row">
    <div class="form-group col-md-12">
        @Html.Partial("~/Areas/Teams/Views/TeamMember/_List.cshtml", this.Model.Members, null)
        @Html.ValidationMessageFor(model => model.Members)
    </div>
</div>
  
<script type="text/javascript">
  
    function buildData() {
        // Get the form values into simple key value array
        var formData = getFormObj();
        var gridData = $("#teamMemberGrid").data("kendoGrid").dataSource.data();
  
        // Prepare the model
        return {
            TeamDetailId: formData["TeamDetailId"],
            TeamCode: formData["TeamCode"],
            TeamDesc: formData["TeamDesc"],
            TeamName: formData["TeamName"],
            Members: gridData,
            Dto: formData["Dto"]
        };
    }
  
    $(function () {
        $("form").on("submit", function (event) {
            event.preventDefault();
            var request = buildData();
            submitForm(request, this.action);
        });
    });
  
</script>

TeamMemberGrid cshtml
<div>
    @(Html.AjaxGridFor<TeamMemberModel>("teamMemberGrid", "Teams", "TeamMember")
        .ToolBar
        (
            toolbar =>
            {
                if (Html.ShowEditControls())
                {
                    toolbar.Template("<a class='k-button k-button-icontext ' href='' id='customGridAdd'><span></span>New</a><span></span>");
                }
            }
        )
        .Columns
        (
            columns =>
            {
                if (Html.ShowEditControls())
                {
                    columns.Command(commands =>
                    {
                        commands.Custom("Edit").Text("Edit").Click("onGridEdit");
                        commands.Custom("Delete").Text("Delete").Click("onGridDelete");
                    });
                }
            }
        )
        .BuildAjaxDataSource<TeamMemberModel>("TeamMember", updateAction: "UpdateMember", createAction: "AddMember", destroyAction: "RemoveMember")
    )
 
    <script type="text/javascript">
 
        function onGridEditing(e) {
            var id = $('#TeamDetailId').val();
            if (e.model.isNew()) {
                e.model.set("TeamDetailId", id);
                e.model.set("TeamMemberId", kendo.guid());
            }
            setPopupTitle(e);
            setGridPopupButtons(e);
        }
 
        //set username, first name, last name
        function onGridSaving(e) {
            var data = e.sender.dataSource.data();
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                if (item.TeamMemberId === e.model.TeamMemberId) {
                    item.set('Username', $('Username').val());
                }
            }
        }
 
        function onGridDelete(e) {
            var grid = $("#teamMemberGrid").data("kendoGrid");
            var row = $(e.currentTarget).closest("tr");
            grid.removeRow(row);
        }
 
    </script>
</div>

Popup View cshtml
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.UserDetailId)
    @Html.EditorFor(model => model.UserDetailId)
    @Html.ValidationMessageFor(model => model.UserDetailId)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.EffectiveFromDate)
    @Html.EditorFor(model => model.EffectiveFromDate)
    @Html.ValidationMessageFor(model => model.EffectiveFromDate)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.EffectiveToDate)
    @Html.EditorFor(model => model.EffectiveToDate)
    @Html.ValidationMessageFor(model => model.EffectiveToDate)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.FirstName)
    @Html.EditorFor(model => model.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName)
</div>
@Html.HiddenFor(model => model.TeamMemberId)
@Html.KendoScripts()
 
 
<input id="Username" name="Username" data-val="true" data-bind="value:Username" type="hidden" value="">
<input id="FirstName" name="FirstName" data-val="true" data-bind="value:FirstName" type="hidden" value="">
<input id="LastName" name="LastName" data-val="true" data-bind="value:LastName" type="hidden" value="">

AutoComplete cshtml
    function onUserAutoCompleteChange(e) {
        var dataItem = $("#@this.ViewData.ModelMetadata.PropertyName").data("kendoDropDownList").dataItem();
 
        $("#Username").val(dataItem.Username);
        $("#FirstName").val(dataItem.FirstName);
        $("#LastName").val(dataItem.LastName);
    }
</script>

TeamMemberController
/// <summary>
/// For use with Kendo Grid ajax binding
/// Creates new models by inserting the data posted by the Kendo Grid into the grid datasource.
/// </summary>
/// <param name="products">The model created by the user.</param>
/// <returns>The inserted model so the Kendo Grid is aware of the newly generated model</returns>
[HttpPost]
public virtual ActionResult AddMember([DataSourceRequest]DataSourceRequest request, TeamMemberModel model)
{
    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}

Thanks in advance

2 Answers, 1 is accepted

Sort by
0
Accepted
Daniel
Telerik team
answered on 15 Sep 2014, 07:22 AM
Hello Michael,

You should trigger the change event after setting the new values.
$("#Username").val(dataItem.Username).trigger("change");
$("#FirstName").val(dataItem.FirstName).trigger("change");
$("#LastName").val(dataItem.LastName).trigger("change");
The val method does not trigger the change event by default and the grid model will not be updated if the event is not triggered.

Regards,
Daniel
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Michael
Top achievements
Rank 1
answered on 15 Sep 2014, 09:46 AM
That works perfectly. Thanks for the help Daniel.

Cheers
Tags
Grid
Asked by
Michael
Top achievements
Rank 1
Answers by
Daniel
Telerik team
Michael
Top achievements
Rank 1
Share this question
or