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

Ajax Bound Grid with ViewData for EditorTemplate

6 Answers 563 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Stephen
Top achievements
Rank 1
Stephen asked on 30 Apr 2014, 09:03 PM
I have a server bound grid that was working fine.  I needed to change it to an ajax bound grid because I needed to add some custom command buttons.  The editor template for the grid contains a dropdownlist which is populated via ViewData in my controller get method.  When I switch the grid to be ajax bound that dropdownlist is throwing an error:

The ViewData item that has the key 'Proposal_Type_ID' is of type 'System.Int32'
but must be of type 'IEnumerable<SelectListItem>'.<BR>

Do I need to change the way the dropdownlist is populated? Or am I doing something else wrong?


Controller:
public ActionResult GetResearchQuestions([DataSourceRequest]DataSourceRequest request)
{
    User user = new User();
    int user_id = user.GetUserIDByBNLAccount(User.Identity.Name);
    string user_facility_id = UserSession.LastViewedUserFacilityID;
 
    if (UserPermissions.VerifyUserFacility(user_id, user_facility_id))
    {
        using (PASSEntities context = new PASSEntities())
        {
            var vm = (from a in context.Proposal_Research_Questions
                      join b in context.Proposal_Types on a.Proposal_Type_ID equals b.ID
                      where b.User_Facility_ID == user_facility_id
                      orderby a.Sort_Order
                      select new ResearchQuestionViewModel()
                      {
                          ID = a.ID,
                          Proposal_Type_ID = a.Proposal_Type_ID,
                          Proposal_Type_Description = b.Description,
                          Question = a.Question,
                          Type = a.Type,
                          Options = a.Options,
                          Required = a.Required,
                          Active = a.Active
                      }).ToList();
 
            var proposalTypes = (from a in context.Proposal_Types
                                 where a.User_Facility_ID == user_facility_id
                                 select a).ToList();
 
            ViewData["ProposalTypes"] = proposalTypes.Select(m => new SelectListItem { Value = m.ID.ToString(), Text = m.Description }).ToList();
 
            DataSourceResult result = vm.ToDataSourceResult(request);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
    else
    {
        return RedirectToAction("Index");
    }
}


View:
@{
    ViewBag.Title = "Research Questions";
}
 
<h2>Proposal Research Questions</h2>
 
@Html.Partial("LastViewedUserFacility")
 
@{ Html.Kendo().Grid<PASSAdmin.ViewModels.UserFacilityAdmin.ResearchQuestionViewModel>()
    .Name("ResearchQuestions")
    .Columns(columns =>
    {
        columns.Command(command => { command.Edit(); }).Width(50);
        columns.Bound(m => m.Question);
        columns.Bound(m => m.Proposal_Type_Description).Title("Proposal Type");
        columns.Bound(m => m.Required).ClientTemplate("#= Required ? '<img src=\\'/Content/images/icons/check.png\\'' : '' #");
        columns.Bound(m => m.Active).ClientTemplate("#= Active ? '<img src=\\'/Content/images/icons/check.png\\'' : '' #");
        columns.Command(command => command.Custom("SortUp").Click("sortUp"));
        columns.Command(command => command.Custom("SortDown").Click("sortDown"));
        columns.Command(command => { command.Destroy(); }).Width(50);
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("UserFacilityAdmin/ResearchQuestion").Window(window => window.Width(500)))
    .Pageable()
    .Sortable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(m => m.ID))
        .Create(create => create.Action("AddResearchQuestion", "UserFacilityAdmin"))
        .Read(read => read.Action("GetResearchQuestions", "UserFacilityAdmin"))
        .Update(update => update.Action("UpdateResearchQuestion", "UserFacilityAdmin"))
        .Destroy(destroy => destroy.Action("DeleteResearchQuestion", "UserFacilityAdmin"))
    )
    .Render();
}
 
<script type="text/javascript">
function sortUp(e) {
    e.preventDefault();
    var id = this.dataItem($(e.currentTarget).closest("tr")).id;
    $.post('/UserFacilityAdmin/UpdateResearchQuestionSortOrder', { id: id, sortChange: -1 }, function (data) {
        $('#ResearchQuestions').data('kendoGrid').dataSource.read();
    });
}
function sortDown(e) {
    e.preventDefault();
    var id = this.dataItem($(e.currentTarget).closest("tr")).id;
    $.post('/UserFacilityAdmin/UpdateResearchQuestionSortOrder', { id: id, sortChange: 1 }, function (data) {
        $('#ResearchQuestions').data('kendoGrid').dataSource.read();
    });
}
</script>



EditorTemplate: (the first field is the one causing the error)
@model PASSAdmin.ViewModels.UserFacilityAdmin.ResearchQuestionViewModel
 
<div class="editor-label">
    @Html.Label("Proposal Type")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Proposal_Type_ID,  (List<SelectListItem>) ViewData["ProposalTypes"], "(Select One)")
    @Html.ValidationMessageFor(model => model.Proposal_Type_ID)
</div>
 
<div class="editor-label">
    @Html.Label("Question")
</div>
<div class="editor-field">
    @Html.TextAreaFor(model => model.Question, new { style = "width:300px;height:50px;" })
    @Html.ValidationMessageFor(model => model.Question)
</div>
 
<div class="editor-label">
    @Html.Label("Type")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Type, new SelectList(Model.QuestionTypes, "Value""Text"), "(Select One)")
    @Html.ValidationMessageFor(model => model.Type)
</div>
 
<div class="editor-label">
    @Html.Label("Options")
</div>
<div class="editor-field">
    @Html.TextAreaFor(model => model.Options, new { style = "width:300px;height:50px;" })
    @Html.ValidationMessageFor(model => model.Options)
</div>
 
<div class="editor-label">
    @Html.Label("Required")
</div>
<div class="editor-field">
    @Html.CheckBoxFor(model => model.Required)
    @Html.ValidationMessageFor(model => model.Required)
</div>
 
<div class="editor-label">
    @Html.Label("Active")
</div>
<div class="editor-field">
    @Html.CheckBoxFor(model => model.Active)
    @Html.ValidationMessageFor(model => model.Active)
</div>










6 Answers, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 02 May 2014, 12:15 PM
Hello Stephen,

This doesn't seem related to Kendo UI in particular. Could it be the problem described in this stackoverflow question?

Regards,
Atanas Korchev
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Stephen
Top achievements
Rank 1
answered on 02 May 2014, 02:12 PM
Well I thought it was related because it is a kendo grid using an editor template and it works fine when the grid is in server bound mode but throws the error in Ajax bound mode.

If I need a dropdown list populated for use in a grid editor template when the grid is Ajax bound, how do I populate that in my controller?

I also saw other posts where people were using a kendo dropdown list and there is a way to bind view data to that I think with bindTo?
0
Atanas Korchev
Telerik team
answered on 02 May 2014, 02:36 PM
Hello Stephen,

The sample application includes such an example. You can check the "Controllers/Grid/Editing_CustomerController.cs" file as well as ~/areas/razor/web/grid/EditorTemplates/ClientCategory.schtml" and ~/areas/razor/web/grid/editing_custom.cshtml".


Regards,
Atanas Korchev
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Stephen
Top achievements
Rank 1
answered on 05 May 2014, 02:24 PM
Hi,

Thanks for pointing me in that direction.  I have modified my code to try to match that and I am not getting the error anymore, but now on grid create or edit the dropdownlist is just empty.  Any ideas?

Here is the updated code.  My View is unchanged from above.  I didn't think I needed to set the default value as the example shows since the example is using inline editing and I am using the editor template.

Controller:
public ActionResult GetResearchQuestions([DataSourceRequest]DataSourceRequest request)
{
    User user = new User();
    int user_id = user.GetUserIDByBNLAccount(User.Identity.Name);
    string user_facility_id = UserSession.LastViewedUserFacilityID;
 
    if (UserPermissions.VerifyUserFacility(user_id, user_facility_id))
    {
        using (PASSEntities context = new PASSEntities())
        {
            var vm = (from a in context.Proposal_Research_Questions
                      join b in context.Proposal_Types on a.Proposal_Type_ID equals b.ID
                      where b.User_Facility_ID == user_facility_id
                      orderby a.Sort_Order
                      select new ResearchQuestionViewModel()
                      {
                          ID = a.ID,
                          Proposal_Type_ID = a.Proposal_Type_ID,
                          Proposal_Type_Description = b.Description,
                          Question = a.Question,
                          Type = a.Type,
                          Options = a.Options,
                          Required = a.Required,
                          Active = a.Active
                      }).ToList();
 
            var proposal_types = (from a in context.Proposal_Types
                                 where a.User_Facility_ID == user_facility_id
                                 select new ProposalTypeViewModel
                                 {
                                     ID = a.ID,
                                     Description = a.Description
                                 }).ToList();
 
            ViewData["ProposalTypes"] = proposal_types;
 
            DataSourceResult result = vm.ToDataSourceResult(request);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
    else
    {
        return RedirectToAction("Index");
    }
}

Gird Popup Editor Template (just the updated field):
@(Html.Kendo().DropDownListFor(model => model.Proposal_Type_ID).Name("Proposal_Type_ID").DataValueField("ID").DataTextField("Description").BindTo((System.Collections.IEnumerable)ViewData["ProposalTypes"]).OptionLabel("(Select One)"))
@Html.ValidationMessageFor(model => model.Proposal_Type_ID)

0
Accepted
Atanas Korchev
Telerik team
answered on 06 May 2014, 02:31 PM
Hello Stephen,

The code which populates the proposal types should be executed in your main action method (the one which renders the view that contains the grid) instead of the one which returns JSON for the grid.

Something like this (assuming that method is called Index):

public ActionResult Index()
{
    var proposal_types = (from a in context.Proposal_Types
         where a.User_Facility_ID == user_facility_id
         select new ProposalTypeViewModel
         {
               ID = a.ID,
               Description = a.Description
         }).ToList();
  
  ViewData["ProposalTypes"] = proposal_types;
 
  return View();
}

Regards,
Atanas Korchev
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Stephen
Top achievements
Rank 1
answered on 06 May 2014, 06:01 PM
Ah yes of course.  Got it now thanks!
Tags
Grid
Asked by
Stephen
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Stephen
Top achievements
Rank 1
Share this question
or