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

[Solved] Insert Ajax combo in Grid column - cell edit mode

0 Answers 176 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Ian
Top achievements
Rank 1
Ian asked on 10 May 2011, 08:58 PM

Hi

I have a MVC3 application with a view that I have added a Telerik Grid to. I am using Telerik.Web.Mvc 2011.1.414.340. I have implemented in-line cell editing/batch editing mode and I would like to use an usercontrol editor template with a combo box for one of the columns (SuggestedValue).
Here is my view;

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Frontline.ETL.Web.UI.ViewModels.Transform.TransformData>" %>
  
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ETL Application - Transform
</asp:Content>
  
<asp:Content ID="ContentMainContent" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        function Grid_onError(args) {
            if (args.textStatus == "modelstateerror" && args.modelState) {
                var message = "Errors:\n"; $.each(args.modelState, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function ()
                        { message += this + "\n"; });
                    }
                }); args.preventDefault(); alert(message);
            }
        }
  
        function Grid_onDataBinding(e) {
            var grid = $(this).data('tGrid');
            if (grid.hasChanges()) {
                if (!confirm('You are going to lose any unsaved changes. Are you sure?')) {
                    e.preventDefault();
                }
            }
        }
  
        function onPossibleValuesComboBinding(e) {
            var selectedRow = $("#RuleConflictGrid tr.t-state-selected");
            var dataItem = $("#RuleConflictGrid").data("tGrid").dataItem(selectedRow);
            var fieldId = dataItem.UnderlyingTableColumnId;
  
            e.data = $.extend({}, e.data, { underlyingFieldId: fieldId });
        }
    </script>
  
    <h2>Transform Data - Run Rules</h2>
    <% using (Html.BeginForm())
    {
        if (Model.CurrentProjectId.HasValue && Model.CurrentProjectId.Value > 0)
        { %>
            <fieldset>
            <%= Html.ValidationSummary(true)%>                   
    
            <%= Html.Telerik().Grid<ETL.Models.DTO.RuleConflictDTO>()
            .Name("RuleConflictGrid")
            .DataKeys(keys => keys.Add(model => model.RuleConflictId))
            .Editable(editing => editing.Mode(GridEditMode.InCell))
            .ToolBar(commands =>
            {
                commands.SubmitChanges();
            })
            .Pageable(paging => paging
                .PageSize(10)
                .Style(GridPagerStyles.NextPreviousAndNumeric)
                .Position(GridPagerPosition.Bottom))
            .Columns(columns =>
            {
                columns.Bound(model => model.DataRuleName).Title("Rule Name");
                columns.Bound(model => model.UnderlyingFieldName).Title("Field");
                columns.Bound(model => model.OriginalValue).Title("Original Value");
                columns.Bound(model => model.SuggestedValue).Title("Suggested Value");
                columns.Bound(model => model.ActualValue).Title("Actual Value");
                columns.Bound(model => model.AcceptOriginalValue).Title("Accept Original Value")
                    .ClientTemplate("<input type='radio' name='AcceptSuggestion' <#= AcceptOriginalValue? checked='checked' : '' #> />");
                columns.Bound(model => model.AcceptSuggestedValue).Title("Accept Suggested Value")
                    .ClientTemplate("<input type='radio' name='AcceptSuggestion' <#= AcceptSuggestedValue? checked='checked' : '' #>/>");
  
            })
            .ClientEvents(events => events.OnDataBinding("Grid_onDataBinding").OnError("Grid_onError"))
            .DataBinding(dataBinding => 
                dataBinding.Ajax()
                .Select("_SelectBatchEditing", "Transform")
                .Update("_SaveBatchEditing", "Transform")
            )        
            %>
                </fieldset>
            <%
        }
        else
        { %>
            Please select a Current Project.
        <%}
    }//Html.BeginForm%> 
  
</asp:Content>

Here is the controller;

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using ETL.Data.EntityClasses;
using ETL.Models.DTO;
using ETL.Web.UI.Helpers;
using Telerik.Web.Mvc;
  
namespace ETL.Web.UI.Controllers
{
    public class TransformController : ControllerBase
    {
        #region Run Rule Checks
  
        public ActionResult Index()
        {
            return View();
        }
  
        public ActionResult TransformData()
        {
            // Ian van der Walt: Create an instance of the ViewModel to pass back to the View
            ViewModels.Transform.TransformData transformDataModel = new ViewModels.Transform.TransformData();
  
            return View(transformDataModel);
        }
  
          
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TransformData(ViewModels.Transform.TransformData transformDataModel)
        {
            try
            {
                GeneralRepository.PerformFactRuleChecks(this.CurrentProjectId.Value);
  
                // Ian van der Walt - 06/05/2011: Update the ProjectETLStatus
                base.RefreshCurrentProjectETLStatus(this.CurrentProjectId);
            }
            catch (Exception ex)
            {
                SetViewModelErrorMessage(transformDataModel, ex.Message);
            }
  
            return View(transformDataModel);
        }
  
        #endregion
  
        #region Rule Conflict Grid
  
        public ActionResult EditingBatch() { return View(); }
  
        [GridAction]
        public ActionResult _SelectBatchEditing()
        {
            return View(new GridModel(GeneralRepository.GetRuleConflictDTOList(this.CurrentProjectId.GetValueOrDefault(0))));
        }
  
        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _SaveBatchEditing(
            [Bind(Prefix = "inserted")]IEnumerable<RuleConflictDTO> insertedProducts,
            [Bind(Prefix = "updated")]IEnumerable<RuleConflictDTO> updatedProducts,
            [Bind(Prefix = "deleted")]IEnumerable<RuleConflictDTO> deletedProducts)
        {
            // TODO: Ian van der Walt - 10/05/2011: Add logic to save changes
  
            return View(new GridModel(GeneralRepository.GetRuleConflictDTOList(this.CurrentProjectId.GetValueOrDefault(0))));
        }
  
        /// <summary>
        /// Gets the possible values list by project id and field id.
        /// </summary>
        /// <param name="projectId">The project id.</param>
        /// <param name="underlyingFieldId">The underlying field id.</param>
        /// <returns></returns>
        /// <remarks>Ian van der Walt</remarks>
        public ActionResult GetPossibleValuesListByProjectIdAndFieldId(string text, Guid underlyingFieldId)
        {
            return Json(GeneralRepository.GetPossibleValuesList(this.CurrentProjectId.Value, underlyingFieldId), JsonRequestBehavior.AllowGet);
        }
  
        #endregion
  
    }
}

(the Rule Conflict Grid region contains the applicable methods).
The grid is currently loading and binding correctly but I would like to use Ajax binding for the combo as well and I am unable to get the combo to display in the grid. I am also not exactly sure how to pass an additional parameter to the Action method that populates the combo - the value must come from the currently selected row.
Here is the usercontrol (which I have created as SuggestedValue.ascx in the \Views\Shared\EditorTemplates folder);

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Frontline.ETL.Models.DTO.RuleConflictDTO>" %>
<%= Html.Telerik().ComboBox()
    .Name("SuggestedValue")
    .ClientEvents(e => e.OnDataBinding("onPossibleValuesComboBinding"))
    .DataBinding(binding => binding.Ajax().Select("GetPossibleValuesListByProjectIdAndFieldId", "Transform")
    .Cache(true))
%>
<%: Html.HiddenFor(m => m.UnderlyingTableColumnId)%>

I was hoping that by adding <%: Html.HiddenFor(m => m.UnderlyingTableColumnId)%> to the usercontrol, I would be able to retrieve it in the client-side onPossibleValuesComboBinding event on the view and thereby pass it as an additional custom parameter to my GetPossibleValuesListByProjectIdAndFieldId action method that returns the Json result.

Is it possible to do this? I would really prefer above all else to be able to do batch editing one way or another as there will be a significant number of rows that the user will need to work through and individual editing and updating would be a real obstacle.

Any assistance or advice would be greatly appreciated.

Thanks!

Ian van der Walt.

Tags
Grid
Asked by
Ian
Top achievements
Rank 1
Share this question
or