Search code examples
asp.netasp.net-mvcteleriktelerik-mvc

Using Telerik in asp.net mvc - Multiselect


Im new to asp.net mvc, and im trying telerik on a project for a client.

I'm trying to add this to my project and i get the Select customers box with a infinite loading icon rotating.

Something like this:

enter image description here

I would like to know how i "bind" data to the control so i display a list of users like in their website example.

so far i tried creating this method in the HomeController

public ActionResult GetCustomers([DataSourceRequest] DataSourceRequest request)
{    
    string jstring = "[{\"CustomerID\": \"ALFKI\", \"ContactName\": \"Maria Anders\" ,\"CompanyName\": \"Alfreds Futterkiste\"}]";

    var obj = JsonConvert.DeserializeObject<List<userTest>>(jstring);
    return Json(obj);
}

and i have this class:

public class userTest
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string CompanyName { get; set; }
}

and this is my index.cshtml:

<div class="demo-section">
    <h3 class="title">Select customers</h3>
    @(Html.Kendo().MultiSelect()
          .Name("customers")
          .DataTextField("ContactName")
          .DataValueField("CustomerID")
          .DataSource(source =>
          {
              source.Read(read =>
              {
                  read.Action("GetCustomers", "Home");
              });
          })
          .Height(300)
          .HtmlAttributes(new { style = "width: 400px" })
          ...
          .ItemTemplate("<span class=\"k-state-default\"><img src=\"" + Url.Content("http://yarris.design/images/userCentered.png") +" /> </span>" + "<span class=\"k-state-default\"><h3>#: data.ContactName #</h3><p>#: data.CompanyName #</p></span>")
          .TagTemplate("<img class=\"tag-image\" src=\"" +
          Url.Content("http://yarris.design/images/userCentered.png") +
          "\" alt=\"\" />" +
          "#: data.ContactName #")
    )
</div>

<script>
    $(document).ready(function() {
        var customers = $("#customers").data("kendoMultiSelect");
        customers.wrapper.attr("id", "customers-wrapper");
    });
</script>

Solution

  • Well, first of all, you don't need that dataSourceRequest as a parameter. You need to return a Json with the dataTextField and the DataValueField.

    I don't know what is returned to your obj variable, so the last line (with linq) must not match exactly what's in it, but I think you'll get the point.

    public ActionResult GetCustomers()
    {
        string jstring = "[{\"CustomerID\": \"ALFKI\", \"ContactName\": \"Maria Anders\" ,\"CompanyName\": \"Alfreds Futterkiste\"}]";
        var obj = JsonConvert.DeserializeObject<List<userTest>>(jstring);
        return Json(obj.Select(s => new userTest { ContactName = s.ContactName, CustomerID = s.CustomerID }).Distinct(), JsonRequestBehavior.AllowGet);
    }