Search code examples
c#asp.net-mvcasp.net-mvc-4kendo-uikendo-autocomplete

DataValueField Missing in kendo Autocomplete


I am using kendo autocomplete control in my MVC project(Server side filtering).It list the data correctly. But the problem is when i submit the data to server the autocomplete value id is missing. Because there is no DataValueField attribute in this control. The bellow code is i am using

@(Html.Kendo().AutoComplete()
    .Name("Patient")
    .Placeholder("Enter Name")
    .DataTextField("TextField")
    .Filter("contains")
    .MinLength(3)
    .HtmlAttributes(new { style = "width:100%" })
    .DataSource(source =>
    {
      source.Read(read =>
      {
         read.Action("function", "controller")
         .Data("onAdditionalData");
      })
         .ServerFiltering(true);
  })
)

How can i send the value to the server.

Thank you..


Solution

  • Since AutoComplete helper doesn't have DataValueField attribute, you need to use other HTML helper as workaround to pass another property value. Suppose your viewmodel has this setup:

    public class ViewModel
    {
        // ID property example
        public int PatientID { get; set; }
    
        // other properties
    }
    

    You can create a hidden field or read-only textbox to store ID property mentioned above inside Razor view:

    @Html.HiddenFor(m => m.PatientID)
    

    Then, assign its value attribute from client-side script by creating a function which reads item index from autocomplete helper:

    function selectPatient(e) {
        var item = this.dataItem(e.item.index());
        $('#PatientID').val(item.PatientID);
    }
    

    And finally set the function name bound for Events attribute:

    @(Html.Kendo().AutoComplete()
        .Name("Patient")
        .Placeholder("Enter Name")
        .DataTextField("TextField")
        .Filter("contains")
        .MinLength(3)
        .HtmlAttributes(new { style = "width:100%" })
    
        // add this line
        .Events(ev => ev.Select("selectPatient"))
    
        .DataSource(source => {
            source.Read(read => {
                read.Action("function", "controller")
                .Data("onAdditionalData");
            })
            .ServerFiltering(true);
        })
    )
    

    By following this setup, the PatientID property should have ID of the selected value from autocomplete helper when user submitted the form.