Icemanind
Icemanind

Reputation: 48686

Loading values into a Kendo MVC Multiselect

I am trying to preload my multiselect with values. I cannot seem to find an example of this that uses Ajax as the datasource. Here is my view code:

@(Html.Kendo().MultiSelectFor(model => model.CompanyIds)
    .Name("CompanyIds")
    .AutoClose(false)
    .AutoBind(false)
    .Placeholder("Select companies...")
    .DataTextField("CompanyName")
    .DataValueField("CompanyId")
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetAvailableCompanies", "Admin");
        }).ServerFiltering(true);
    })
    .HtmlAttributes(new { @class = "form-control" })
)

And here is my controller code:

    public ActionResult Portals()
    {
        var portals = new Portals();
        portals.GetBySqlStatement("SELECT * FROM Portal WHERE IsDeleted = 0");
        var adminPortals = portals.Select(portal => new Infrastructure.ViewModels.AdminPortal
        {
            PortalName = portal.PortalName,
            PortalId = portal.PortalId,
            CompanyIds = new List<int> { 1 }
        }).ToList();

        return View(adminPortals);
    }

Here is my GetAvailableCompanies method:

public virtual JsonResult GetAvailableCompanies([DataSourceRequest] DataSourceRequest request)
{
    var companies = new Companys();

    companies.GetBySqlStatement("SELECT * FROM Company WHERE IsDeleted=0 ORDER BY CompanyName");

    return Json(companies, JsonRequestBehavior.AllowGet);
}

I tried adding .Value(new List<int> {1}) to the end of the multiselect, but it doesn't select it. I think the issue is that, because its Ajax, the value doesn't "yet exist" in the multiselect. Does anyone know the proper way to handle this? I tried looking for an event on the multiselect that executes after databinding, also with no luck.

EDIT

My view is using this model:

@model AdminPortal

and here is the class definition:

public class AdminPortal
{
    public int PortalId { get; set; }

    [Display(Name = "Portal Name")]
    [Required(ErrorMessage = "Portal Name is required")]
    public string PortalName { get; set; }

    public List<int> CompanyIds { get; set; }
}

Upvotes: 0

Views: 1568

Answers (1)

user3559349
user3559349

Reputation:

Change

.AutoBind(false)

to

.AutoBind(true)

Side note: The .Name("CompanyIds") option is not required since your using and expression (.MultiSelectFor(m => m.CompanyIds)) which will add the name="CompanyIds" attribute anyway.

Upvotes: 2

Related Questions