Telerik Forums
UI for ASP.NET MVC Forum
6 answers
428 views
I'm evaluating the Grid control for use in a project. I've searched the documentation and demos and haven't been able to figure out whether it is possible to customize the Filter UI to look something similar to the first attached screenshot. It doesn't need to be exact, but I'd like to be able to remove the operators list and label text.

I also tried using a multiselect (which might be ok as an alternative to check boxes), but I don't know how to wire it up so that it filters properly.

@(
    Html.Kendo().Grid<User>()
    .Name("grid")
    .Pageable(config => config
        .Info(true)
    )
    .Sortable()
    .Filterable()
    .ColumnMenu(config =>
        config.Enabled(true))
    .Columns(config =>
    {
        config.Bound(user => user.Id);
        config.Bound(user => user.FirstName);
        config.Bound(user => user.LastName);
        config.Bound(user => user.UserName);
        config.Bound(user => user.Type)
            .ClientTemplate("#=Type#")
            .Filterable(filter => filter
                .UI("typeFilter")
                .Extra(false)
            );
    }
        )
    .DataSource(dataSourceBuilder => dataSourceBuilder
        .WebApi()
        .Read(config => config
                .Url("/api/data/users")
        )
         
        )
      )
----
 
<script type="text/javascript">
    function typeFilter(element) {
        element.kendoMultiSelect(
        {
            dataTextField: "name",
            dataValueField: "id",
            dataSource: {
                data: [
                    { id: 1, name: "Builder"},
                    { id: 2, name: "Police Man"}
                ]
            }
        });
    }
</script>

Is what I'm trying to achieve possible? Can someone point me in the right direction?
Dimo
Telerik team
 answered on 18 Aug 2015
2 answers
68 views

Hi Kendo,

 

Building user-controls - or controls that may be added on many pages throughout a website - how is this done with Kendo?

I can think of - at least - 3 different types of usercontrols:

  1. A simple control like the DateTimePicker
  2. A stand-alone control with a model and a control
  3. A ClientDetailTemplateId (found in Html.Kendo().Grid)

Is it possible to build those 3 types of controls so they may be re-used in more than one page ?

Thank you.

Hristo Valyavicharski
Telerik team
 answered on 18 Aug 2015
3 answers
961 views
Hi,

I'm working on a grid (somewhat similar, but also a bit different in terms of underlying model) again. I'm having issues with creating a new record.

Whenever I press the "Add new record" button, nothing happens and the browser console says the following:
Uncaught ReferenceError: CustomerContract is not defined.

Here's my grid and relevant templates in the razor view:
<script type="text/kendo" id="customerTemplate">
    #if(data != null){#
    #:data.Name#
    #}#
</script>
 
<script type="text/javascript">
    var customerTemplate = kendo.template($("#customerTemplate").html(), { useWithBlock: false });
</script>
 
<div class="container">
    <div class="row">
        <div class="col-md-12 sl-table">
            @(Html.Kendo().Grid<ProjectModel>()
                  .Name("grid")
                  .Columns(columns =>
                  {
                      columns.Bound(p => p.Name);
                      columns.Bound(p => p.CustomerContract).ClientTemplate("#=customerTemplate(CustomerContract)#");
                      columns.Command(command =>
                      {
                          command.Edit();
                          command.Destroy();
                      }).Width(180);
                  })
                  .ToolBar(toolbar => toolbar.Create())
                  .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("ProjectPopUpTemplate"))
                  .Pageable()
                  .Sortable()
                  .Scrollable()
                  .HtmlAttributes(new {style = "height:500px;"})
                  .DataSource(dataSource => dataSource
                      .Ajax()
                      .PageSize(10)
                      .Events(events => events.Error("error_handler"))
                      .Model(model => model.Id(p => p.Id))
                      .Create(update => update.Action("EditingPopup_Create", "ProjectManagement"))
                      .Read(read => read.Action("EditingPopup_Read", "ProjectManagement"))
                      .Update(update => update.Action("EditingPopup_Update", "ProjectManagement"))
                      .Destroy(destroy => destroy.Action("EditingPopup_Destroy", "ProjectManagement"))
                  )
                  )
        </div>
    </div>
</div>
Now, the grid populates fine, and the edit button works. It's only an issue when pressing the "Add new record" button.
Here's how my controller looks (removed the update / destroy actions):
public class ProjectManagementController : BaseController
    {
        static readonly ILog Log = LogManager.GetLogger("ProjectManagementController.class");
        private static readonly List<Customer> CustomerList = new List<Customer>();
        public ProjectServiceClient ProjectService { get; set; }
        public CustomerServiceClient CustomerService { get; set; }
        public ProjectModel Model { get; set; }
 
        public ProjectManagementController()
        {
            try
            {
                ProjectService = new ProjectServiceClient();
                CustomerService = new CustomerServiceClient();
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
 
        // GET: ProjectManagement
        public ActionResult Projects()
        {
            List<CustomerContract> customers = CustomerService.GetCustomers().ToList();
            Model = new ProjectModel();
            foreach (var customer in customers)
            {
                CustomerList.Add(new Customer
                {
                    Name = customer.Name,
                    Id = customer.Id
                });
            }
 
            ViewData["Customers"] = GetAll();
 
            return View(Model);
        }
 
        public ActionResult EditingPopup_Read([DataSourceRequest] DataSourceRequest request)
        {
            ProjectContract[] list = ProjectService.GetProjects();
            return Json(list.ToDataSourceResult(request));
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingPopup_Create([DataSourceRequest] DataSourceRequest request, ProjectModel project)
        {
            if (project != null && ModelState.IsValid)
            {
                CustomerContract customer = CustomerService.GetCustomer(project.CustomerContract.Id);
                var newProject = ProjectService.InsertProject(new ProjectContract
                {
                    CustomerContract = customer,
                    Name = project.Name,
                    Id = project.Id
                });
 
                ProjectService.UpdateProject(newProject);
            }
 
            return Json(new[] { project }.ToDataSourceResult(request, ModelState));
        }
    }
The service call in the read method returns a list of ProjectContracts. A ProjectContract consists of a few properties of type string and another property of type CustomerContract (which holds its own string properties). Could this nested contract possibly be the problem?

Finally, here's my model which the grid is based on:   
public class ProjectModel
{
    private ProjectContract _projectContract;
 
    public ProjectModel(ProjectContract projectContract)
    {
        ProjectContract = projectContract;
    }
 
    public ProjectModel()
    {
    }
 
    public CustomerServiceClient CustomerService { get; set; }
 
    private ProjectContract ProjectContract
    {
        get
        {
            if (_projectContract == null)
            {
                _projectContract = new ProjectContract();
            }
 
            return _projectContract;
        }
        set { _projectContract = value; }
    }
 
    [Display(Name = "Customer")]
    public CustomerContract CustomerContract
    {
        get
        {
            if (ProjectContract.CustomerContract == null)
            {
                return new CustomerContract();
            }
 
            return ProjectContract.CustomerContract;
        }
        set { ProjectContract.CustomerContract = value; }
    }
 
    [Display(Name = "Customers")]
    public List<Customer> Customers { get; set; }
 
    [ScaffoldColumn(false)]
    public int Id
    {
        get { return ProjectContract.Id; }
        set { ProjectContract.Id = value; }
    }
 
    [Display(Name = "Project Name")]
    public string Name
    {
        get { return ProjectContract.Name; }
        set { ProjectContract.Name = value; }
    }
}

How can I go about solving this?
Boyan Dimitrov
Telerik team
 answered on 18 Aug 2015
1 answer
159 views

Hello there,

I have a grid set up and I'd like to change the row and or cell style based on the value of a particular column.  For example a field had a value of "live" the row would be green or alternatively thee would be a green icon next word "live".  Can the grid do this? I had a look at templates but they don't seem to be specific enough or perhaps I wasn't understanding them.  I don't need any CSS/styling advice I just need to know if the grid can assign a class or whatever to the cell or row based on a single field data and if so how?

Dimiter Madjarov
Telerik team
 answered on 18 Aug 2015
2 answers
107 views

When use Grid edit command without calling GridActionColumnFactory.Edit(). GridBuilder would not render localization script for the popup edit. Just like the code.​

@(Html.Kendo().Grid<ProduceViewModel>()
    .Name("grid")
    .DataSource(datasource=>
        /*...*/
    )
    .Columns(columns =>
    {
        columns.Bound(m => m.ProductId).ClientTemplate("<a onclick='edit(this)'>#=ProductId#</a>");
        columns.Bound(m => m.ProductName);
        columns.Command(command =>
        {
            command.Destroy();
        });
    })
)

Daniel
Telerik team
 answered on 18 Aug 2015
2 answers
224 views

Entity Model for Country (All models are in a separate project)

 

[ScaffoldColumn(false)]
public int CountryId { get; set; }
public string ShortName { get; set; }
public string LongName { get; set; }
public string IsoCode2 { get; set; }
public string IsoCode3 { get; set; }
public string IsoCodeHash { get; set; }
public string CallingCodeOne { get; set; }
public string CallingCodeTwo { get; set; }
public string CurrencyName { get; set; }
public string CurrencySymbol { get; set; }
public List<State> States { get; set; }
 

Entity Model for State 

 

[ScaffoldColumn(false)]
public int StateId { get; set; }
public string Name { get; set; }
public bool IsCapital { get; set; }
 
[ScaffoldColumn(false)]
public int CountryId { get; set; }
public Country Country { get; set; }

 

States Controller deriving from ODataController (It's a separate project)

 

private DataAccess.Helper.DatabaseContext _dbContext;
 
public StatesController()
{
    DataAccess.MyApp.StartUp.Initialize();
 
    const string dataSource = "My-PC\\SQLEXPRESS";
    const string initialCatalog = "BS";
 
    var connString = SqlConnection.CreateConnectionString("", dataSource, initialCatalog);
 
    _dbContext = new DatabaseContext(connString);
}
 
// GET odata/Countries
[EnableQuery]
public System.Linq.IQueryable<State> GetStates()
{
    return _dbContext.States;
}
 
public IHttpActionResult Put([FromODataUri] int key, State entity)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
     
 
    if (key != entity.StateId)
        return BadRequest();
 
    _dbContext.States.Attach(entity);
    _dbContext.Entry(entity).State = EntityState.Modified;
 
    try
    {
        _dbContext.SaveChanges();
    }
    catch (Exception)
    {
        if (!EntityExists(key))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }
 
    return Updated(entity);
}
 
private bool EntityExists(int key)
{
    return _dbContext.States.Count(e => e.StateId == key) > 0;
}
 
public IHttpActionResult Post(State entity)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
 
    _dbContext.States.Add(entity);
    _dbContext.SaveChanges();
    return Created(entity);
}

 

View (It's in a separate project)

@(Html.Kendo().Grid<SC.BS.EntityModel.State>()
      .Name("EntityStates")
      .Columns(col =>
      {
          col.Bound(e => e.StateId);
          col.Bound(e => e.Name).Title("State").Width("200");
          col.Bound(e => e.IsCapital).Title("Capital").Filterable(false).Width(100).ClientTemplate("#= IsCapital ? 'Yes':'No' #").HtmlAttributes(new {style="align=center"});
          col.Bound(e => e.CountryId);
          col.Bound(e => e.Country).Title("Country").ClientTemplate("#: Country.ShortName #").EditorTemplateName("CountriesLookUp").Filterable(false);
          col.Command(cmd =>
          {
              cmd.Edit();
              cmd.Destroy();
          }).Width(170);
      })
      .Scrollable()
      .ToolBar(tb => tb.Create().Text("New State"))
      .DataSource(ds => ds
          .Custom()
          .Schema(sch =>
          {
              sch.Model(m =>
              {
                  m.Id("StateId");
                  m.Field(e => e.StateId).Editable(false);
                  m.Field(e => e.CountryId).DefaultValue(1);
                  //m.Field(e => e.Country).DefaultValue(new SC.BS.EntityModel.Country());
                  //m.Field("CreatedOn", typeof(DateTime));
              });
          })
          .Type("odata-v4")
          .Transport(tr =>
          {
              tr.Read(r => r.Url("http://localhost:28016/oData/States").Data("function() {return {'$expand' : 'Country'} }"));
              tr.Create(c => c.Url("http://localhost:28016/oData/States"));
              tr.Update(new
              {
                  url = new Kendo.Mvc.ClientHandlerDescriptor
                  {
                      HandlerName = @"function(data) {
                                            return 'http://localhost:28016/oData/States(' + data.StateId + ')';
                                       }"
                  }
              });
              tr.Destroy(new
              {
                  url = new Kendo.Mvc.ClientHandlerDescriptor
                  {
                      HandlerName = @"function(data) {
                                            return 'http://localhost:28016/oData/States(' + data.StateId + ')';
                                       }"
                  }
              });
          })
          .PageSize(20)
          .ServerPaging(true)
          .ServerSorting(true)
          .ServerFiltering(true)
      )
      .Pageable()
      .Sortable()
      .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
      .Editable(e => e.Mode(GridEditMode.InLine)))

 

CountriesLookUp EditorTemplate

@model SC.BS.EntityModel.Country
 
@(Html.Kendo().DropDownList().Name("Countries").DataSource(ds => ds
    .Custom()
    .Schema(sch =>
    {
        sch.Model(m =>
        {
            m.Id("CountryId");
        });
    })
    .Type("odata-v4")
    .Transport(tr =>
    {
        tr.Read(r => r.Url("http://localhost:28016/oData/Countries"));
    })
 
)
.DataValueField("Country")
.DataTextField("ShortName"))

 

 

Displaying data works fine, but I'am having trouble updating the State.

  1. When I click edit, DropDown preselect top/first country instead of selecting the country that state belongs to.
  2. After changing values, update doesn't work, my ​Web​AP complaints in Put method that the ModelState is invalid and errors out:
  3. message=entity : The property 'Countries' does not exist on type 'SC.BS.EntityModel.State'. Make sure to only use property names that are defined by the type.
  4. This is the JSON that is sent on update command.
    {"StateId":"1","Name":"Delhi","IsCapital":true,"CountryId":"2","Country":{"CountryId":2,"ShortName":"United States","LongName":"United States of America","IsoCode2":"US","IsoCode3":"USA","IsoCodeHash":"840","CallingCodeOne":"1","CallingCodeTwo":"","CurrencyName":"USD","CurrencySymbol":"$"},"Countries":"United States"}
Boyan Dimitrov
Telerik team
 answered on 18 Aug 2015
4 answers
610 views

I want to persist what child detail grid is open on return to the page. I tried using the localstorage example

var options = kendo.stringify(grid.getOptions())
     localStorage.setItem("kendo-grid-options", options);

but this does not seem to keep the open expanded row details.

Is there an event that fires when oi expand a row, then maybe I could use that to record the row number and expand using js when page is loaded, thanks

Dimiter Madjarov
Telerik team
 answered on 17 Aug 2015
2 answers
103 views

I have very large data sets I want to display in a grid, and I'd like to use the auto filtering on the column header.  But with my large data sets, users will typically want to specify a few filters before getting their data, otherwise the retrieval of the records from the database takes a very long time.

It seems that by default, each filter in the grid is applied immediately.  I'd like to allow the user to select multiple filters, and then push a button to trigger the refresh.

Is there a good way to skip the automatic refresh that comes with setting a filter in the grid header?

 

Brian
Top achievements
Rank 1
 answered on 14 Aug 2015
2 answers
100 views

Hi

I have installed a trial version to have a play around with the Scheduler control.

I have put together a basic ​page, but have a problem when attempting to edit an event.  After double clicking on the event, the event dialog opens. Then, whenever I hit Cancel or the close (X) button, I get the following error:

 Unhandled exception at line 10, column 30735 in kendo.all.min.js

Javascript runtime error: unable to get property 'uid' of undefined or null reference.

The Save button works fine. 

 I am using Kendo.Mvc.dll 2015.2.805.545, and Visual Studio 2013.

 Any ideas on why this is failing?

Cheers, Jarrod

Jarrod
Top achievements
Rank 1
 answered on 14 Aug 2015
8 answers
176 views
Hello,

like the title reveals, I need to display data, that is updated irregularly, but at least once every few seconds.

Is it possible to bind the Chart to a SignalR hub, like it is for the grid? (http://demos.telerik.com/aspnet-mvc/grid/signalr)
Which other approaches promise good and efficient results? Polling of WebAPI? A separat SignalR function and adding data to chart on client side?

Thank you in advance.
Robert
Top achievements
Rank 1
 answered on 14 Aug 2015
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
MultiSelect
ListView
Window
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Template
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Licensing
Localization
MultiViewCalendar
PopOver (Mobile)
Ripple
ScrollView (Mobile)
Switch (Mobile)
PivotGridV2
FlatColorPicker
ColorPalette
DropDownButton
AIPrompt
PropertyGrid
ActionSheet (Mobile)
BulletGraph
Button (Mobile)
Collapsible
Loader
CircularGauge
SkeletonContainer
Popover
HeatMap
Avatar
ColorGradient
CircularProgressBar
SplitButton
StackLayout
TimeDurationPicker
Chip
ChipList
DockManager
ToggleButton
Sankey
OTPInput
ChartWizard
SpeechToTextButton
InlineAIPrompt
TimePicker
StockChart
RadialGauge
ContextMenu
ArcGauge
AICodingAssistant
+? more
Top users last month
Ambisoft
Top achievements
Rank 2
Iron
Pascal
Top achievements
Rank 2
Iron
Matthew
Top achievements
Rank 1
Sergii
Top achievements
Rank 1
Iron
Iron
Andrey
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Ambisoft
Top achievements
Rank 2
Iron
Pascal
Top achievements
Rank 2
Iron
Matthew
Top achievements
Rank 1
Sergii
Top achievements
Rank 1
Iron
Iron
Andrey
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?