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

[Solved] condition in grid

9 Answers 165 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Howard
Top achievements
Rank 1
Howard asked on 16 Jan 2012, 12:09 AM
In the grid the same column should sometimes work as textbox and sometimes as dropdownlist.
how to make it possible in 1 grid in 1 column. i think may be with jquery but i don't know how to do... 
Please find the following code and where i want the result is in bold

@(Html.Telerik().Grid<ParametersSelectModel>()
            .Name("DefaultList")
            .Sortable(sorting => sorting.Enabled(true))
            .Pageable(paging =>
                    paging.PageSize(12)
                    .Style(GridPagerStyles.NextPreviousAndNumeric)
                    .Position(GridPagerPosition.Bottom))
            .Footer(true)
            .DataBinding(dataBinding => dataBinding.Ajax().Select("_DefaultList", "Parameters").Update("_DefaultListEdit", "Parameters"))
          
            .DataKeys(keys => keys.Add(p => p.PARAMETER_ID))
            .Filterable(filtering => filtering.Enabled(true))
            .Reorderable(reorder => reorder.Columns(true))


            .Columns(columns =>
            {
                columns.Bound(p => p.NUMBER).Title("Number").Width(80).ReadOnly();
                columns.Bound(p => p.SHORT_DESCRIPT).Title("Short Description").Width(400);
                columns.Bound(p => p.LONG_DESCRIPT).Title("Long Description").ReadOnly();
                columns.Bound(p => p.DEFAULT_VALUE).Title("Value");
// here sometimes i want value as TEXTBOX & sometimes i want value as DROPDOWN LIST...
                columns.Bound(p => p.GRIDID).Hidden(true);
                columns.Bound(p => p.MODULE).Title("Module").ReadOnly();
                columns.Command(commands =>
                {
                    commands.Edit().ButtonType(GridButtonType.Text);


                }).Width(200).HeaderHtmlAttributes(new { @style = "font-weight:bolder;" }).Title("Commands");
                
            })


           .Editable(editing => editing.Mode(GridEditMode.InLine))
        
            )

9 Answers, 1 is accepted

Sort by
0
Accepted
John DeVight
Top achievements
Rank 1
answered on 16 Jan 2012, 08:48 PM
Hi Niroj,

The approach that I would take is to first setup the "DEFAULT_VALUE" column as a DropDownList box using an Editor Template.  I would then add a client event handler for the OnEdit event.  In the client event handler, I would apply the logic necessary to determine whether it should be changed to a textbox.

I've attached a sample application to demonstrate.  In the sample application, I will display a dropdownlist of colors for the "DEFAULT_VALUE" column.  If the name of the person is 'John Doe', then I will change the dropdownlist to a textbox.  Here is what I did:

I've got a model class called Person that looks like this:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
  
namespace TelerikMvcGridEditingDropdown.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
  
        [UIHint("DefaultValue")]
        public string DEFAULT_VALUE { get; set; }
    }
}

The "DEFAULT_VALUE" property will be either a dropdownlist or a textbox in the grid.  I've added the UIHint attribute and passed in a value of "DefaultValue".  This is used to determine the name of the Editor Template to use.  The Editor Template is in a folder called EditorTemplates and is called DefaultValue.cshtml.  The code for the DefaultValue.cshtml is:

@model string
  
@(
    Html.Telerik().DropDownListFor(e => e).BindTo(new SelectList(ViewBag.HairColors))
)

The values for the DropDownList are defined in the ViewBag in the HomeController.  Here is the code:

namespace TelerikMvcGridEditingDropdown.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult ConditionInGrid()
        {
            ViewBag.HairColors = new string[] { "Brown", "Black", "Red", "Blonde" };
            return View("ConditionInGrid", GetPeople());
        }
   
        private IList<Person> GetPeople()
        {
            IList<Person> people = null;
  
            if (Session["People"] == null)
            {
                people = new List<Person>();
                people.Add(new Person { Id = 1, Name = "John Doe", DEFAULT_VALUE = "Brown" });
                people.Add(new Person { Id = 2, Name = "Jayne Doe", DEFAULT_VALUE = "Black" });
            }
            else
            {
                people = Session["People"] as List<Person>;
            }
  
            return people;
        }
    }
}

The ConditionInGrid.cshtml view defines a grid called PeopleGrid.  The grid defines the event handler for the OnEdit client event:

@{
    Html.Telerik().Grid(Model)
        .Name("PeopleGrid")
        .DataKeys(keys => keys.Add(m => m.Id))
        .Columns(columns =>
        {
            columns.Bound(m => m.Name);
            columns.Bound(m => m.DEFAULT_VALUE);
            columns.Command(c => c.Edit());
        })
        .DataBinding(db => db.Ajax().Update("UpdatePerson", "Home"))
        .ClientEvents(events => events.OnEdit("onEdit"))
        .Render();
}

The onEdit event handler contains the logic the determins whether to change the DropDownList to a TextBox.  The parameter passed to onEdit, e, has a property called dataItem.  dataItem contains the values that are being edited.  When a row is being edited, a form is created.  The name of the form is the name of the grid plus the word form.  So, in the grid defined above, PeopleGrid, the name of the form is PeopleGridfirm.  The name of the DropDownList control will be the name of the model property.  In this case, the name would be DEFAULT_VALUE.  If the name of the person being edited is John Doe, I locate the DropDownList and get the value that is to be displayed.  I then replace the DropDownList with a TextBox and set the value of the TextBox to the value that was in the DropDownList:

onEdit = function (e) {
    if (e.dataItem.Name == 'John Doe') {
        var value = $('#DEFAULT_VALUE').data('tDropDownList').value();
        $('#PeopleGridform.t-edit-form').find('#DEFAULT_VALUE').closest('div.t-dropdown')
            .replaceWith($('<input/>').attr('id', 'DEFAULT_VALUE').attr('name', 'HairColor').val(value));
    }
}

Attached is a sample application.  Let me know if you have any questions.

Regards,

John DeVight
0
Howard
Top achievements
Rank 1
answered on 17 Jan 2012, 11:13 PM
Thank u very much it works fine!!!

0
John DeVight
Top achievements
Rank 1
answered on 18 Jan 2012, 01:10 AM
Glad to hear =) If you have a moment, could you mark my post as the answer? Thanks. Regards, John
0
Howard
Top achievements
Rank 1
answered on 18 Jan 2012, 01:26 AM
I really appreciate your solution.

also can we use here different dropdown lists based on condition in the same column of grid?

like in the following script  if my table name is TBL_A then bind that if it is TBL_B then bind that and likewise...
<script type="text/javascript">
    function onEdit(e) {
        if ($(e.form).find('#GRIDID').attr('value') == 0) {
            var value = $('#DEFAULT_VALUE').data('tDropDownList').value();
            $('#DefaultListform.t-edit-form').find('#DEFAULT_VALUE').closest('div.t-dropdown')
                .replaceWith($('<input/>').attr('id', 'DEFAULT_VALUE').attr('name', 'HairColor').val(value));
        }
        else {            
            var ColumnsSelected = $('#TBL_NAME').attr('value')           
            var dataSend = { 'Cols': ColumnsSelected };
            $.ajax({
                url: '/Parameters/ColumnsSelected',
                type: 'POST',
                data: JSON.stringify(dataSend),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data, status, xhr) {
                    location.reload();
                },
                error: function (xhr, status, error) {
                    $('#MessageBar').html('Error ocurred: ' + status);
                }
            });
            
        }
    }    
</script>
in the controller:
 public ActionResult ColumnsSelected(string Cols)
        {
           
            var context = new AUSFLEETEntities();
            if (Cols == "PFL_OWNERSHIP")
            {
                ViewBag.HairColors = (from o in context.PFL_OWNERSHIP select o.OWNERSHIP_USER_CODE);               
                return PartialView("_DefaultParameters");
            }
            else  if (Cols == "PFL_LESSOR ") 

            {
                ViewBag.HairColors = (from o in context.PFL_LESSOR select o.LESSOR_ID );
                return PartialView("_DefaultParameters");
            }
         }
but i am unable to call EditorTemplate DefaultValue again once it is bind. 
any solution for this?
0
John DeVight
Top achievements
Rank 1
answered on 18 Jan 2012, 06:22 PM
Hi Niroj,

Unfortunately I don't know what to do in that situation =(

Regards,

John
0
Georgi Tunev
Telerik team
answered on 19 Jan 2012, 04:04 PM
Hi guys,

 Niroj, I am not quite sure that I understand your scenario completely. Could you please provide a sample project where your current setup is shown? This will give us a better idea of what your exact setup and requirements are.

Thank you in advance.

Regards,
Georgi Tunev
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
0
Donna Stewart
Top achievements
Rank 1
answered on 07 Jun 2012, 04:01 PM
Hi,

I really appreciate John's solution as it is ALMOST working for me.  I need either a dropdownlist or a textbox in the PropertyValue column depending upon the value of the PropertyName column in the grid.  The dropdownlist data is different depending upon that PropertyName column.  I have all of this working, except the textbox.  The column does become a textbox when it is supposed to and I can change the text, but when I click out of it, it changes back to the initial value.  I am using incell (batch) editing, so this may be the reason, but I can't for the life of me figure out how to fix it.  I am still learning javascript and jquery.  Oh, and this is in a hierarchical grid in a tabstrip as well.  Does anyone have an idea of how I might fix this?

Thanks in advance for any help!

Donna

Here's the Editor Template:
<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
 
<%= Html.Telerik().DropDownList().Name("PropertyValue")%>

Here's the Model:
Imports System.ComponentModel.DataAnnotations
Public Class WQInputPropertyModel
    Public Property WQIP_Key As Integer
    Public Property WQI_Key As Integer
    <UIHint("DisplayTypeTemplate")>
    Public Property PropertyValue As String
    Public Property PropertyName As String
    Public Property NoEdit As Boolean
    Public Property display_data_Types As List(Of SelectListItem)
End Class

Here's the controller code:
<GridAction()>
Function GetInputProperties(ByVal wqid As Integer, ByVal wqipid As Integer, ByVal queryType As com.gmcps.GMCQueryPermission.WebQueryTypes, ByVal rptName As String) As ActionResult
    Dim gmcPermissions As New GMCQueryPermission
    Dim statusReturn As New StatusReturn
    Dim wqInputProps As New List(Of WQInputPropertyModel)
    Dim webQueryInputs As New List(Of WebQueryInput)
    Dim displaydataTypes As New List(Of SelectListItem)
    Dim dispdataTypes As New List(Of String)
    statusReturn = gmcPermissions.GetWebQueryInputs(queryType, webQueryInputs, wqid, rptName)
    If statusReturn.StatusCode.Equals(com.gmcps.StatusReturn.StatusCodes.SUCCESS) Then
        For Each wqInput In webQueryInputs
            If wqInput.WQI_Key = wqipid Then
                wqInputProps = New List(Of WQInputPropertyModel)
                For Each wqip In wqInput.WebQueryInputProperties.ToList
                    dispdataTypes = New List(Of String)
                    displaydataTypes = New List(Of SelectListItem)
                    If wqip.PropertyName.ToUpper.Equals("DATATYPE") Then
                        statusReturn = gmcPermissions.GetInputPropertiesDataTypes(dispdataTypes)
                    ElseIf wqip.PropertyName.ToUpper.Equals("DISPLAYTYPE") Then
                        statusReturn = gmcPermissions.GetInputPropertiesDisplayTypes(dispdataTypes)
                    End If
                    If statusReturn.StatusCode.Equals(com.gmcps.StatusReturn.StatusCodes.SUCCESS) Then
                        For Each dt In dispdataTypes
                            displaydataTypes.Add(New SelectListItem With {.Text = dt, .Value = dt})
                        Next
                    End If
                    wqInputProps.Add(New WQInputPropertyModel With {.WQIP_Key = wqip.WQIP_Key, .WQI_Key = wqip.WQI_Key, .PropertyValue = wqip.PropertyValue, _
                                                                     .PropertyName = wqip.PropertyName, .NoEdit = If(.PropertyName.ToLower.Contains("name"), True, False), _
                                                                    .display_data_Types = displaydataTypes})
                Next
            End If
        Next
        Return View(New GridModel(wqInputProps))
    End If
    Return PartialView("Error")
End Function

Here's the grid code:
<% Html.Telerik().Grid(Of GMC_Hub_and_Spoke.WebQueryInputModel).Name("InputPropertiesGrid").HtmlAttributes(New With {.style = "width:95%;"}) _
    .DataKeys(Function(key) key.Add(Function(k) k.WQI_Key)) _
    .ToolBar(Function(commands) commands.Insert()) _
    .ToolBar(Function(commands) commands.SubmitChanges()) _
    .ClientEvents(Function(events) events.OnError("onGridError")) _
    .ClientEvents(Function(events) events.OnEdit("onGridEdit")) _
    .ClientEvents(Function(events) events.OnDataBound("replaceWQIDelMsg")) _
    .ClientEvents(Function(events) events.OnLoad("replaceWQIDelMsg")) _
         .DataBinding(Function(dataBinding) dataBinding.Ajax().Select("GetWQInputs", "WebQuery", _
                                                                      New With {.id = Model.QueryKey, .queryType = com.gmcps.GMCQueryPermission.WebQueryTypes.EXISTING, .rptName = Nothing}) _
                          .Update("UpdateWQInputs", "WebQuery", New With {.wqid = Model.QueryKey})) _
         .Editable(Function(editing) editing.Mode(GridEditMode.InCell)) _
         .Columns(Function(cols) cols.Bound(Function(c) c.ParameterName)) _
         .Columns(Function(cols) cols.Bound(Function(c) c.DisplayOrder)) _
         .Columns(Function(cols) cols.Command(Function(c) c.Delete()).Title("Delete")) _
         .Columns(Function(cols) cols.Bound(Function(c) c.QueryKey).Hidden(True)) _
         .Columns(Function(cols) cols.Bound(Function(c) c.WQI_Key).Hidden(True)) _
         .DetailView(Function(detailView) detailView.ClientTemplate( _
             Html.Telerik().Grid(Of GMC_Hub_and_Spoke.WQInputPropertyModel).Name("Properties_<#= WQI_Key #>") _
                 .DataKeys(Function(key) key.Add(Function(kk) kk.WQIP_Key)) _
                 .ToolBar(Function(commands) commands.Insert()) _
                 .ToolBar(Function(commands) commands.SubmitChanges()) _
                 .DataBinding(Function(dataBinding) dataBinding.Ajax().Select("GetInputProperties", "WebQuery", _
                                                                              New With {.wqid = Model.QueryKey, .wqipid = "<#= WQI_Key #>", _
                                                                                        .queryType = com.gmcps.GMCQueryPermission.WebQueryTypes.EXISTING, .rptName = Nothing}) _
                                  .Update("UpdateInputProperties", "WebQuery", New With {.wqid = Model.QueryKey, .wqinputid = "<#= WQI_Key #>"})) _
                 .Editable(Function(editing) editing.Mode(GridEditMode.InCell)) _
                 .ClientEvents(Function(events) events.OnEdit("onWQIPGridEdit")) _
                 .ClientEvents(Function(events) events.OnDataBound("replaceWQIDelMsg")) _
                 .ClientEvents(Function(events) events.OnLoad("replaceWQIDelMsg")) _
                 .ClientEvents(Function(events) events.OnRowDataBound("onWQIPRowDataBound")) _
                 .Columns(Function(col) col.Bound(Function(cc) cc.PropertyName)) _
                 .Columns(Function(col) col.Bound(Function(cc) cc.PropertyValue)) _
                 .Columns(Function(col) col.Command(Function(cc) cc.Delete()).Title("Delete")) _
                 .Columns(Function(col) col.Bound(Function(cc) cc.NoEdit).Hidden(True)) _
                 .Columns(Function(col) col.Bound(Function(cc) cc.WQI_Key).Hidden(True)) _
                 .Columns(Function(col) col.Bound(Function(cc) cc.WQIP_Key).Hidden(True)) _
                 .ToHtmlString())).Render()
%>

Here's the onEdit (onWQIPGridEdit) code:
function onWQIPGridEdit(e) {
    var mode = e.mode;
    var form = e.form;
    var cell = e.cell;
    if (e.mode == "edit") {
        if (cell.cellIndex != 0) {
            if (e.dataItem.PropertyName == "DATATYPE" || e.dataItem.PropertyName == "DISPLAYTYPE") {
                var combo = $(e.form).find("#PropertyValue").data("tDropDownList");
 
                if (combo) {
                    var value = combo.value();
 
                    combo.dataBind(e.dataItem.display_data_Types);
                    combo.value(value);
                }
            }
            else {
                var vvalue = $('#PropertyValue').data('tDropDownList').value();
                $(e.form).find('#PropertyValue').closest('div.t-dropdown').replaceWith($('<input/>').attr('id', 'PropertyValue').attr('name', 'OtherValue').val(vvalue));
            }
        }
        else {
            var myPropretyName = $(e.form.PropertyName);
            var myvalue = myPropretyName.val();
            var $newInput = $('<input type="hidden" name="myPropretyName" id="myPropretyName" value="" />' + '<span>' + myvalue + '</span>').val(myvalue);
            myPropretyName.replaceWith($newInput);
        }
    }
}
0
Petur Subev
Telerik team
answered on 12 Jun 2012, 08:12 AM
Hi Donna,

I would suggest you to open a support ticket and share your project in it, so we can have a better view over your setup and investigate what exactly is going wrong.
 
Kind Regards,
Petur Subev
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now.
0
Donna Stewart
Top achievements
Rank 1
answered on 14 Jun 2012, 05:44 PM
Thank you Petur.  I actually ended up using in-line editing instead of cell/batch editing.  It works great with in-line editing.

Thanks again,
Donna
Tags
General Discussions
Asked by
Howard
Top achievements
Rank 1
Answers by
John DeVight
Top achievements
Rank 1
Howard
Top achievements
Rank 1
Georgi Tunev
Telerik team
Donna Stewart
Top achievements
Rank 1
Petur Subev
Telerik team
Share this question
or