Telerik Forums
UI for ASP.NET MVC Forum
3 answers
964 views
Hi,

I'm working on a user management system in asp.net mvc, where I display all my users in a grid using KendoUI. However, I have a string based list of user roles, which I need to display as a dropdown in my edit view. Since my view is generated based on my model, I'm not really sure how to accomplish this.

Here's how my model looks like:
public class UserModel
{
    #region Properties
    [Display(Name = @"Username")]
    [Required]
    public string UserName { get; set; }
    [Required]
    public string Name { get; set; }
    [Display(Name = @"E-mail")]
    [EmailAddress]
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    [DataType(DataType.Password)]
    [Display(Name = @"Password")]
    [Required]
    public string PasswordHash { get; set; }
    [Display(Name= @"Roles")]
    public List<string> UserRoles { get; set; }
    [ScaffoldColumn(false)]
    public string UserRoleIcon { get; set; }
    [ScaffoldColumn(false)]
    public string UserRoleIconInverted { get; set; }
 
    #endregion
 
    public UserModel()
    {
         
    }
 
    public UserModel(UserContract userContract)
    {
        SetupUserModel(userContract);
    }
 
    private void SetupUserModel(UserContract userContract)
    {
        UserName = userContract.UserName;
        Name = userContract.Name;
        Email = userContract.Email ?? "";
        Phone = userContract.Phone ?? "";
        Company = userContract.Company ?? "";
        PasswordHash = userContract.PasswordHash ?? "";
        UserRoles = new List<string>();
 
        if (userContract.UserRoles != null)
        {
            foreach (var userRole in userContract.UserRoles)
            {
                UserRoles.Add(userRole);
            }
        }
 
        SelectUserRoleIcon(UserRoles);
    }
 
    // TODO: Hierarchy on roles and selecting images?
    private void SelectUserRoleIcon(IEnumerable<string> userRoles)
    {
        foreach (var userRole in userRoles)
        {
            switch (userRole.ToLower())
            {
                case "administrator":
                    UserRoleIcon = "Administrator.png";
                    UserRoleIconInverted = "Administrator_Black.png";
                    break;
                case "operator":
                    UserRoleIcon = "Operator.png";
                    UserRoleIconInverted = "Operator_Black.png";
                    break;
                case "supervisor":
                    UserRoleIcon = "Supervisor.png";
                    UserRoleIconInverted = "Supervisor_Black.png";
                    break;
                default:
                    UserRoleIcon = "Guest.png";
                    UserRoleIconInverted = "Guest_Black.png";
                    break;
            }
        }
    }
}

Here's my grid:
@(Html.Kendo().Grid<Stimline.Xplorer.Services.Models.User.UserModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.UserName);
            columns.Bound(p => p.Name);
            columns.Bound(p => p.Email);
            columns.Bound(p => p.Phone);
            columns.Bound(p => p.UserRoles);
            columns.Command(command => { command.Edit(); }).Width(160);
        })
        .ToolBar(toolbar => toolbar.Create())
        .Editable(editable => editable.Mode(GridEditMode.PopUp))
        .Pageable()
        .Sortable()
        .Scrollable()
        .HtmlAttributes(new { style = "height:430px;" })
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(20)
            .Events(events => events.Error("error_handler"))
            .Model(model => model.Id(p => p.UserName))
            .Create(update => update.Action("EditingPopup_Create", "UserManagement"))
            .Read(read => read.Action("EditingPopup_Read", "UserManagement"))
            .Update(update => update.Action("EditingPopup_Update", "UserManagement"))
            //.Destroy(update => update.Action("EditingPopup_Destroy", "Grid"))
        )
    )

I don't really need to display the column with selected roles in the grid, but what I do need is the possibility to add / edit them from the popup. Preferably as a multiselect list, as a user could have several roles. I've tried following this example, but can't seem to manage to get it right.
See the attached images for a description of how it looks now.

Vladimir Iliev
Telerik team
 answered on 20 May 2014
1 answer
735 views
I'm working on an application which I have now almost finished but I have one thing that I really need to sort out before I release. I return a dataset of around 600 rows to the grid. I then chose to Edit one of these rows and change the value in a ComboBox Editor template. For example, I might change it from Jan Jones to John Smith.

This all works fine at the database level. However, when I press Update the values displayed in the Display template are still Jan Jones and not John Smith. So far, the only way I've been able to get this to work is by using a dataSource refresh in the onSync event. However, this is taking at least 15 seconds to reload the entire grid.I guess it is returning the entire dataset and not just the currently displayed page.  

Presumably, I am doing something wrong somewhere but I am not sure where. Any help would be most useful as I have been scratching my head on this for a while now.

Controller
01.public JsonResult GetTestDetailed([DataSourceRequest] DataSourceRequest request)
02.{
03.                var testTable = dataAccessLayer.GetDataTable("select statement here");
                          //testTable will be about 600 rows
04.                var testDictionary = (from DataRow row in testTable.Rows select testTable.Columns.Cast<DataColumn>  ().ToDictionary(column => column.ColumnName, column => row[column].ToString())).ToList().AsQueryable();
05.                return Json(testDictionary.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
06.            }
07.        }
08.         
09.    [AcceptVerbs(HttpVerbs.Post)]
10.        public ActionResult Update([DataSourceRequest] DataSourceRequest request, TestDirectoryDetail testDetail)
11.        {
12.        dataAccessLayer.Update(testDetail);
13.            return Json(new[] { testDetail }.ToDataSourceResult(request, ModelState));
14.        }


Grid

01.<script type="text/javascript">
02.    function onSync(e) {
03.        var grid = $('#TestGrid').data('kendoGrid');
04.        grid.dataSource.read();
05.    }
06.</script>
07. 
08.@(Html.Kendo().Grid((IEnumerable<DirectoryDetail>)ViewBag.Details)
09.    .Name("TestGrid")
10.     .HtmlAttributes(new { style = "height:850px;" })
11.    .Editable(editable => editable.Mode(GridEditMode.InLine))
12.    .Events(e => e.SaveChanges("onSaveChanges"))
13.    .Filterable()
14.    .Groupable()   
15.    .Pageable() // Enable pageing
16.    .Scrollable(scr=>scr.Height("auto"))
17.    .Sortable() // Enable sorting
18.    .DataSource(dataSource => dataSource
19.            .Ajax()
20.            .Events(events => events.Error("error_handler").Sync("onSync"))
21.            .PageSize(15)
22.            .Model(model =>
23.            {
24.                model.Id(p => p.Id);
25.            })
26.            .Update(update => update.Action("Update", "Home"))
27.            .Read(read => read.Action("GetPracticesDetailed", "Home"))
28.        )
29.    .Columns(columns =>
30.    {
31.        columns.Bound(m => m.PracticeId).Title("Id");
32.        columns.Bound(m => m.PayManager).Width(150).Title("DPM").Template(m => m.PayManager).EditorTemplateName("PayManagerDropDown").ClientTemplate("#:PayManager#");
33.        columns.Command(command => command.Edit()).Title("Actions");
34.    })           
35.    .Resizable(resize => resize.Columns(true)))

Dropdown
01.@(Html.Kendo().ComboBox()
02.        .Name("PayManagerId")
03.        .Filter(FilterType.StartsWith)
04.        .HtmlAttributes(new {style = "width:auto;"})
05.        .Placeholder("Type beginning of name to select new pay manager")
06.        .DataTextField("FullName")
07.        .DataValueField("userid")
08.        .AutoBind(true)
09.        .Suggest(true)
10.        .DataSource(source => source.Read(read => read.Action("GetUsers", "Home")).ServerFiltering(false)))


Rosen
Telerik team
 answered on 20 May 2014
3 answers
2.1K+ views
Hi,

I would like to hide a specific row in a Kendo UI MVC Grid. Can anybody please help me in this.

---Satish
Alexander Popov
Telerik team
 answered on 19 May 2014
5 answers
239 views
I have a grid with ClientTemplate columns which render to buttons for navigating to other MVC pages.  The first column renders to:
<td role="gridcell"><a href="/WebPortal/Patient/GetPatient/500507" class="btn btn-sm">View Patient</a></td>

However, when I add the .Events parameter, then the ClientTemplate columns do not work and render as:
<td>500507</td>

I want to execute a DataBound event but it messes up the columns.  Any ideas?  Code follows:
​
@(Html.Kendo().Grid(Model)
        .Name("PatientSearchGrid")
        .Columns(columns =>
        {
            columns.Bound(e => e.LName).Title("Last Name");
            columns.Bound(e => e.FName).Title("First Name");
            columns.Bound(e => e.ReferralDate);
            columns.Bound(e => e.Status);
            columns.Bound(e => e.ID).Hidden();
            columns.Bound(e => e.ID).ClientTemplate(
                "<a href='" + Url.Action("GetPatient", "Patient") + "/#= ID #'" + "class='btn btn-sm'>View Patient</a>"
                ).Width(110).Title("");
            columns.Bound(e => e.ID).ClientTemplate(
                "<a href='" + Url.Action("CreateAccount", "Patient") + "/#= ID #'" + "class='btn btn-sm'>Create Account</a>"
                ).Width(127).Title("");
        })
        .HtmlAttributes(new { style = "height: 390px;" })
        .Pageable(pageable => pageable
             
            .PageSizes(true).PageSizes(new int[] { 20, 50, 100 })
            .ButtonCount(5))
        .Sortable()
        .Filterable()
        .Scrollable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .Sort(s => s.Add(n => n.LName))
            .PageSize(20)
            .ServerOperation(false))
        //.Events(events => events.DataBound("dataBound"))
)
Dimiter Madjarov
Telerik team
 answered on 19 May 2014
2 answers
101 views
I was looking around for an example of how to use the grid control has the datasource for the DataViz control. Would like the pie chart to change based on the filtered data shown in the grid. Thanks
Mike
Top achievements
Rank 1
 answered on 19 May 2014
3 answers
282 views
Hi, 
I´m trying to use a treeview with checkboxes for definition User Rights. (2 actions - enabled/disabled right)
How can I to get value (id) from parent node ?

I attached an example what I need.
Alex Gyoshev
Telerik team
 answered on 19 May 2014
5 answers
221 views
Hi!

We have a grid using popup editing from an ASP editor template - pretty simple. In the popup there is a cascading dropdown (company => department). Our primary goal this time was to auto-select the first entry in the department dropdown on databinding (could this maybe be added as an option of the dropdown in the future?), but when developing this we ran into some MVVM issues. The editor template is similar to this (with an added debug input box to illustrate MVVM behaviour):

@(Html.Kendo().DropDownList()
       .Name("CompanyId")
       .OptionLabel("Choose company")
       .BindTo(MMHtmlHelperExtension.SelectListForCompany(Model != null ? Model.CompanyId : null))
       .HtmlAttributes(new { data_value_primitive = "true" })
      )
 
@(Html.Kendo().DropDownList()
       .Name("DepartmentId")
        .OptionLabel("Choose department") //We would like to remove this, but if this is removed and the dropdown contains only one element that element cannot be selected
       .DataSource(source => source
           .Read(read => read.Action("GetDepartmentsInCompany", "EditorTemplates", new {area = ""}))
           .ServerFiltering(true))
       .Enable(false)
       .AutoBind(false)
       .CascadeFrom("CompanyId")
       .HtmlAttributes(new { data_value_primitive = "true" })
      )
<input id="inputToIllustrateMVVMBehaviour" data-bind="value: DepartmentId" />

To select the first element we tried (in javascript on document ready) using the select() function and the value() function, both of which visibly changed the value of the department dropdown but none of which changed the MVVM value (input value visibly, but more importantly grid ajax post on finishing editing):


departmentDropDownList
            .dataSource
            .bind("change", function(e) {
                    if (departmentDropDownList.select() == 0) {
                        departmentDropDownList.select(1); //Visibly changes the dropdown, but does not update the MVVM value
                        $("#DepartmentId_listbox").children().eq(1).click(); //Extremely hacky workaround that actually works. Selecting a department manually by clicking also works.
                    }
                });

SO - the main questions:

  • Is it possible to make the line "departmentDropDownList.select(1)" actually update the model? Can the update be forced in some way? Isn't that type of code really supposed to work out of the box?
  • Is it possible to access the model of the popup directly? (instead of "dropdown.select(1)" do "popupModel.DepartmentId = theNewId" for example)
  • Also - when adding/updating a grid using popup, the new line's columns "Company name" and "Deparment name" will be empty in this case until the post-back is done (the Id columns will work though). Is it possible to update the Company/Department name values when selecting values in each dropdown?

Best regards
Victor

Vladimir Iliev
Telerik team
 answered on 19 May 2014
11 answers
831 views
Is there anyone one who used kendo ui grid with signalr in an asp.net mvc 4 application? I could not find any sample using them both. I'm trying to develop a sample as in the stock ticker sample. I need any kind of help.

Thanks in advance,
Vladimir Iliev
Telerik team
 answered on 16 May 2014
1 answer
137 views
Hi

Is it possible to override the default ListView styling. In particular I have a grey border around my listview that i'd like to remove.

Thanks
Ant
Top achievements
Rank 1
 answered on 16 May 2014
2 answers
138 views
Hi,

I'm having an issue getting the MonthTemplateID property to function correctly when used with a Kendo DatePicker control. For some reason, the code within the template seems to execute, but the results are different than when I execute the same code from within the .MonthTemplate property. 

The model has as a property a serialized string with shortDateTime strings in it that I use to determine whether or not to highlight a date This is the action that returns the partial view:
[HttpGet]
public PartialViewResult GetSearchPartialView(string projectName)
{
    RawrSearchAreaModel model = new RawrSearchAreaModel();
 
    // get a list of all window dates from DB
    List<DateTime> RunDates;
 
    using (RAWREntities dbcontext = new RAWREntities())
    {
        RunDates = dbcontext.Messages.Where(m => m.ProjectName == projectName).Select(x => x.RunDateTime).Distinct().ToList();
    }
    JavaScriptSerializer jss = new JavaScriptSerializer();
    model.ScheduledDatesJson = jss.Serialize(RunDates.Select(x => x.ToShortDateString()).ToArray());
 
    return PartialView("_rawrSearchArea", model);
}

And here is a working example of a DatePicker that correctly highlights the appropriate dates:
@(Html.Kendo().DatePicker()
    .Name("startDatePicker")
    .Events(events =>
    {
        events.Change("startDateChanged");
    }
    )
    .MonthTemplate("#if ( $.inArray(kendo.toString(new Date(+data.date), 'M/d/yyyy'), " + @Model.ScheduledDatesJson + ") != -1) {#" +
                     "<div class='dateHasWindows'>" +
                    "#}else {#" +
                    "<div>" +
                    "#}#" +
                    "#= data.value #" +
                    "</div>"
    )
 )

However, I have multiple calendar-like controls on the page that need the same date highlighting functionality. Rather than include the same MonthTemplate for each of them, I wanted to create one template and then call it from each of the controls.

Here is how I am attempting to utilize the separate template:
@(Html.Kendo().DatePicker()
    .Name("startDatePicker")
    .Events(events =>
    {
        events.Change("startDateChanged");
    }
    )
    .MonthTemplateId("calendarTemplate")
 )

And here is how I attempted to create the template:
<script id="calendarTemplate" type="text/x-kendo-template">
    #if ( $.inArray(kendo.toString(new Date(+data.date), 'M/d/yyyy'), " + @Model.ScheduledDatesJson + ") != -1) {#
          <div class='dateHasWindows'>
    #}else {#
          <div>
    #}#
    #= data.value #
    </div>
</script>

I inserted an alert into the template to ensure that it was being called and executed, but the formatting is never applied when the template is called this way. For some reason, the inArray function is always returning -1, even when I can see that the date string is in the string that is being compared against (I output the stringified date value, the compare result, and the string array in my alert to verify this).

Am I doing something incorrectly in the template definition that prevents things from executing correctly?
Any help would be appreciated.

Thanks!
Jarrod
Top achievements
Rank 1
 answered on 15 May 2014
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
ComboBox
Upload
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
Accessibility
ListView (Mobile)
Pager
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
DateInput
MediaPlayer
TileLayout
Drawer
SplitView
Template
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Licensing
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
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
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?