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

How to save values entered in ComboBox in Grid Editor PopUp and rebind the ComboBox?

5 Answers 478 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
Shawn
Top achievements
Rank 1
Shawn asked on 06 Mar 2019, 04:53 PM

Hello,

I have a requirement where the user needs to be given the ability to enter custom text inside a ComboBox if the value is not already there.  The ComboBox is bound to a model.  I'm not sure what is the best way to accomplish this.  Currently, in my controller I check to see if the Id of the entered text is equal to 0, and then I update the model data.  I am able to add the new value to the database, afterwards however, I don't know how to refresh/rebind the combobox to show the newly entered data.

Here's my Html-Helper code for the ComboBox:

@(Html.Kendo().ComboBox()
    .Name("SystemType")
    .AutoBind(true)
    .BindTo((System.Collections.IEnumerable)ViewData["SystemTypes"])
    .DataTextField("SystemTypeName")
    .DataValueField("SystemTypeId")
    .Filter(FilterType.Contains)
    .HtmlAttributes(new { style = "width: 350px; background-color: white;" })
    .Placeholder("...")
    .ClearButton(false))

 

Here's the code in my Controller to add a new value:

if (asset.SystemTypeId == 1 || asset.SystemTypeId == 0)
{
    string SystemTypeName = Request.Form["SystemType"];
    if(asset.SystemTypeId == 0 && !string.IsNullOrEmpty(SystemTypeName))
    {
        SystemType systemType = new SystemType()
        {
            ProjectId = Id,
            SystemTypeName = SystemTypeName
        };
 
        _repository.AddSystemType(systemType);
    }
    else
    {
        ModelState.AddModelError("SystemTypeId", "System Type is Required");
    }               
}

Any help is greatly appreciated.  Thanks.

Shawn A.

 

5 Answers, 1 is accepted

Sort by
0
Dimitar
Telerik team
answered on 11 Mar 2019, 11:40 AM
Hello Shawn,

From what I can see, the new SystemType is being correctly added to the database in the corresponding table. After the item is added on the server, you could return its data as JSON to the client-side and then use the dataSource read() method to refresh the data and the use the value() method to select the new item:
var combo = $("#SystemType").getKendoComboBox();

combo.dataSource.read();
combo.value(item);

Regards,
Dimitar
Progress Telerik
Get quickly and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Shawn
Top achievements
Rank 1
answered on 14 Mar 2019, 06:05 PM

Hello Dimitar,

Thank you for your reply!  When you say "After the item is added on the server," how do I go about doing that?  The data is added via the controller, and the ComboBox is bound via "ViewData".  Can I bind the ComboBox both via Ajax and "ViewData"?  I am very new to ASP.NET Core and Kendo UI controls.  I'm not exactly sure how to go about doing what you've suggested.  Is there an example you can provide?  Perhaps I should have mentioned earlier that my ComboBox is inside a Partial View Template for a Grid's PopUp edit mode.  Thanks! 

0
Dimitar
Telerik team
answered on 19 Mar 2019, 01:31 PM
Hello Shawn,

There is no example available that demonstrates the exact scenario described. However, with you current setup, you could try the following:

1) Inside the Editor Template configure a NoDataTemplateId():
@(Html.Kendo().ComboBoxFor(m => m.SystemType)
  ...         
  .NoDataTemplateId("noDataTemplate")
)

2) At the top of the template(this is important in order for the JS function to be available) define the template that will pop up when a custom item is entered in the ComboBox:
<script id="noDataTemplate" type="text/x-kendo-tmpl">
    <div>
        No data found. Do you want to add new item - '#: instance.text() #' ?
    </div>
    <br />
    <button class="k-button" onclick="addNew('#: instance.element[0].id #', '#: instance.text() #')">Add new item</button>
</script>

The above template will cause a button to be displayed for adding a new item. In this way, after a custom item name is entered, the popup is displayed. Thus, this allows us to apply a click handler and add the new item through the dataSource.add() method:
<script>
    function addNew(widgetId, value) {  
        var widget = $("#" + widgetId).getKendoComboBox();
        var dataSource = widget.dataSource;
        
        if (confirm("Are you sure?")) {
            var model = {
                SystemTypeId: 0,
                SystemTypeName: value
            };
 
            $.ajax({
                type: "POST",
                url: "/Home/AddSystemType",
                data: model,
                dataType: "json",
                success: function (response) {
                    var combo = $("#SystemType").getKendoComboBox();
 
                    combo.dataSource.add(response.item);
                     
                },
                error: function (error) {
                }
            });           
        }
    };
</script>

3) Create the respective end-point on the server:
[HttpPost]
public IActionResult AddSystemType(SystemType type)
{
  // Persist the received type in the database
  ...
 
  // Return the item to the client
  return Json(new { result = "success", item = type });
}

Regards,
Dimitar
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Shawn
Top achievements
Rank 1
answered on 19 Mar 2019, 06:10 PM

Hello Dimitar,

Thank you very much for the detailed explanation!  This has helped me a lot!  I've almost got it working on my page.  The only issue I have at the moment is that once the user clicks the "Update" button in the popup template the underlying grid does not get refreshed with the new data.  I have to manually refresh the page to see the changes.  How do I refresh the grid after the update button is pressed so that I can see the new data?

I've tried creating an event in the grid for "RequestEnd" to call the "read" method again, but that doesn't seem to work:

        .DataSource(datasource => datasource
            .Ajax()
            .PageSize(20)
            .Events(events =>
            {
                events.Error("error_handler");
                events.RequestEnd("onRequestEnd");
            })
 
function onRequestEnd(e) {
    if (e.type === "update") {
        $("#grid").data("kendoGrid").dataSource.read();
    }
}

 

Regards,

Shawn A.

0
Dimitar
Telerik team
answered on 21 Mar 2019, 12:59 PM
Hello Shawn,

I am glad to hear that you have managed to progress further with the project requirements. Regarding the follow-up query - make sure that the Grid DataSource schema definition describes the related field and also ensure that the Name() of the ComboBox in the editor template matches the bound column name.

If the above does not help, I would suggest to open a separate support ticker, where you could attach an isolated version of the project. In this way, we will be able to investigate the scenario further and troubleshoot the cause for the issue.

Regards,
Dimitar
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
ComboBox
Asked by
Shawn
Top achievements
Rank 1
Answers by
Dimitar
Telerik team
Shawn
Top achievements
Rank 1
Share this question
or