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

DropDownList Values are Undefined When ActionResult Returns JSON

2 Answers 1066 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Zack
Top achievements
Rank 1
Zack asked on 20 Mar 2013, 08:17 PM
I can't seem to find documentation that will help me to sort this out. I'm trying to populate a DropDownList with the wrapper:

@(Html.Kendo().DropDownList()
          .Name("DropDownListRoles")
          .DataTextField("RoleName")
          .DataValueField("Id")
          .DataSource(datasource => datasource
                                .Read(read => read.Action("GetRoles", "User"))
                                .ServerFiltering(true)
                            )
          .SelectedIndex(0)
         )

The ActionResult method seems straight-forward enough:

public ActionResult GetRoles()
        {
            var roles = UserService.GetRoles();
            return Json(roles.Select(role => new SelectListItem() { Text = role.RoleName, Value = role.Id.ToString() }), JsonRequestBehavior.AllowGet);
        }

The roles are retrieved from the data store, and the JSON seems to be getting sent back to the client, but the values show as "undefined" from the dropdownlist.

If I change ActionResult to JsonResult, I get the same result.

If you could give me some hints as to where my mistake is, I'd be grateful.

Thanks much, and regards...

-Zack

2 Answers, 1 is accepted

Sort by
0
Vladimir Iliev
Telerik team
answered on 22 Mar 2013, 09:56 AM
Hi Zack,

 
From the provided information it seems that the DropDownList is not bind correctly as it expects the data to contain "Id" and "RoleName" fields, however the currently the action returns IEnumerable data with "Text" and "Value" fields. I would suggest to modify the action in the following way:

public ActionResult GetRoles()
{
    var roles = UserService.GetRoles();
    return Json(roles.Select(role => new SelectListItem() { RoleName = role.RoleName, Id = role.Id.ToString() }), JsonRequestBehavior.AllowGet);
}
Kind Regards,
Vladimir Iliev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Accepted
Zack
Top achievements
Rank 1
answered on 22 Mar 2013, 03:03 PM
As it turns out we use AutoMapper to map our business logic components to UI components.

Once I started doing this correctly, I was simply able to return the JsonResult with the roles as a list, and the DropDown wrapper took care of the rest.

public JsonResult GetRoles()
{
var domainRoles = UserService.GetRoles();
var roles = Mapper.Map<IList<UserDomainEntities.Role>, IList<Role>>(domainRoles);
return Json(roles, JsonRequestBehavior.AllowGet);
}
Tags
DropDownList
Asked by
Zack
Top achievements
Rank 1
Answers by
Vladimir Iliev
Telerik team
Zack
Top achievements
Rank 1
Share this question
or