Telerik Forums
UI for ASP.NET MVC Forum
3 answers
893 views

Hi there, Im using MVC 5 and really battling to populate the model with what is currently in the listbox. I have done some research and can see recommendations to use Ajax but surely this should be a basic model binding?

I can pass the selected items correctly back to the controller via the event on add however Im still lost how I can assign this to the DeviceList object within the model. Am I being silly? Many thanks :)

See Model :

    public class DeviceGroupDetailModel
    {
        public int Id { get; set; }
        [Display(Name = "Name")]
        public string Name { get; set; }
        public string Company { get; set; }
        public List<DeviceModelList> DeviceList { get; set; }


        public DeviceGroupDetailModel()
        {
            DeviceList = new List<DeviceModelList>();
        }
    }

See Razor :

(In Create.cshtml)

@using (Html.BeginForm("Create", "DeviceGroups", new { area = "" }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>New group details</h5>
                    </div>
                    <div class="ibox-content">
                        @Html.Partial("_DeviceGroupDetail", Model)
                        @Html.Partial("_DeviceList", Model)
                        <div class="form-group">
                            <div class="col-sm-10">
                                <button class="btn btn-primary" type="submit">Create group</button>
                                &nbsp;|&nbsp;
                                @Html.ActionLink("Cancel", "Index", "DeviceGroups", new { area = "" }, null)
                            </div>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
        var dataSource;
        $(document).ready(function () {
            dataSource = new kendo.data.DataSource({
                serverFiltering: false,
                transport: {
                    read: {
                        url: '@Url.Action("DeviceList_Read", "DeviceGroups")',
                    dataType: "json"
                }
            },
            requestStart: function () {
                kendo.ui.progress($("#alldevicesid"), true);
                kendo.ui.progress($("#selectedid"), true);
            },
            requestEnd: function () {
                kendo.ui.progress($("#alldevicesid"), false);
                kendo.ui.progress($("#selectedid"), false);
            },
            batch: false
        });

        dataSource.fetch(function () {
            var data = this.data();
            var alldevices = $("#alldevices").data("kendoListBox");
            var selected = $("#selected").data("kendoListBox");
            for (var i = 0; i < data.length; i++) {
                alldevices.add(data[i]);
                selected.add(data[i]);
            }
        });
    });

        function onSelectListBoxAdd (e) {
            //debugger
            $.ajax({
                type: "POST",
                url: "/DeviceGroups/SelectedDevices",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ selectedItems: $('#selected').data('kendoListBox').dataItems() }),
                dataType: "json",
                success: function (result) {
                    alert("Successfully sent to server: " + result.map(function (x) {
                        return x.SerialNumber
                    }))
                }
            });
    }
    </script>
}

(In DeviceList partial view)

<div id="alldevicesid" class="col-sm-3">
                        <label for="alldevices" id="all">All Devices</label>
                        @(Html.Kendo().ListBox()
                            .Name("alldevices")
                            .Toolbar(toolbar =>
                            {
                                toolbar.Position(Kendo.Mvc.UI.Fluent.ListBoxToolbarPosition.Right);
                                toolbar.Tools(tools => tools
                                    .TransferTo()
                                    .TransferFrom()
                                    .TransferAllTo()
                                    .TransferAllFrom()
                                );
                            })
                            .DataValueField("DeviceId")
                            .DataTextField("SerialNumber")
                            .Draggable(true)
                            .DropSources("selected")
                            .ConnectWith("selected")
                            .BindTo(new List<DeviceModelList>())
                            .Selectable(ListBoxSelectable.Multiple)
                        )
                    </div>

                    <div id="selectedid" class="col-sm-3">
                        <label for="selected">Selected Devices</label>
                        @(Html.Kendo().ListBox()
                                .Name("selected")
                                .Draggable(true)
                                .DropSources("alldevices")
                                .DataValueField("DeviceId")
                                .DataTextField("SerialNumber")
                                .ConnectWith("alldevices")
                                .BindTo(new List<DeviceModelList>())
                                //.BindTo(Model.DeviceList)
                                .Selectable(ListBoxSelectable.Multiple)
                                .Events(events => events
                                .Add("onSelectListBoxAdd"))
                        )
                    </div>

 

In Controller:

        public ActionResult SelectedDevices(List<DeviceModelList> selectedItems)
        {
            return Json(selectedItems);
        }

        private IEnumerable<DeviceModelList> GetDeviceList()
        {
            List<Device> devices = Managers.DeviceManager.GetList(DevicePart.VCM001, PaginationOptions.NoPaging()).Take(10).ToList();
            return Mapper.Map<IEnumerable<DeviceModelList>>(devices);
        }

        public ActionResult Create()
        {
            return View(new DeviceGroupDetailModel());
        }

        [HttpPost]
        public async Task<ActionResult> Create(DeviceGroupDetailModel model)
        {

        }

David
Top achievements
Rank 1
 answered on 17 Nov 2017
9 answers
916 views
Hi,

I don't know how I can use linq query in bounding a grid column to display a value.

If I use this code

    @(Html.Kendo().Grid<MYMODEL>(Model)
    .Name("myObject")
    .Columns(columns =>
    {
        columns.Bound(ViewBag["myList"].Where(p => p.Value == "2").Text);

I have an error : "cannot  use lamba expression without casting before.

Any help will be very much appreciated

Stefan
Telerik team
 answered on 17 Nov 2017
4 answers
456 views

Hi,

I'm using the Bootstrap v3 Telerik MVC theme.  Can I style the text box Placeholders and dropdown list OptionLabels to have the same default placeholder color?  Right now the defaults for Placeholders are gray and the defaults for OptionLabels are black.

Thanks!

Brian
Top achievements
Rank 2
Iron
 answered on 16 Nov 2017
2 answers
173 views

Is it possible to add a ListBox to a Window?  Tried the below with no joy.  I have dynamically (onclick) created many moveable popup windows.  Within the windows there will be items that I want to allow a user to drag to another popup window. 

I can get the below code to work with a ListView but then I need to make all the hooks to drag items around.  I am trying to take advantage of what already exists.

var w = $("<div>Window</div>");
$("#map").append(w);
var kw = w.kendoWindow({});
var klvb = w.kendoListBox({});

Thanks for any help!

Dimitar
Telerik team
 answered on 15 Nov 2017
1 answer
11.3K+ views

I have an MVC5 application running the latest version of Kendo. I have a ViewModel with a DateTime property:

MyViewModel.cs

private DateTime _startDate;
public DateTime StartDate
{
    get { return _startDate; }
    set
    {
        if (value.Kind == DateTimeKind.Local)
            value = value.ToUniversalTime();
        _startDate = new DateTime(value.Ticks, DateTimeKind.Utc);
    }
}​

And in my controller I am instantiating this VM and setting the StartDate property to UtcNow:

MyController.cs

public virtual ActionResult ​Index()
{
    var vm = new MyViewModel { StartDate = DateTime.UtcNow };
    return View(vm);
}

And in my view I create a KendoDateTimePicker and bind it to my StartDate property in my model:

Index.cshtml

@model MyViewModel
 
@using (Html.BeginForm("Index", "MyController", FormMethod.Post, new { @role = "form" }))
{
    @(Html.Kendo().DateTimePickerFor(x => x.StartDate)
        .Format("yyyy/MM/dd HH:mm")
        .TimeFormat("HH:mm")
    )
    <button type="submit">Submit</button>
}

 The datetimepicker will display the time in UTC, and when the form is submitted the time returned to the controller is in UTC.

 However I'm looking at accomplishing two things:

1. Display local time to the client in the date time picker

2. Return the value of the date time picker in UTC to the server

 This means that somewhere on the client side the conversion from UTC to Local time must be made for display purposes. Then another conversion from Local Time to UTC when posting back the date to the server.

Is there anyway of having the DateTime picker display a local datetime when bound to a UTC date? If not, is there some event or hook I can use to pre-process the value that the datetimepicker is bound to on the client side?

Similar question for when submitting the form. Is there an event or hook I can use to have the value of the datetimepicker be returned as its UTC equivalent?

Stefan
Telerik team
 answered on 15 Nov 2017
1 answer
520 views

Hi,

I'm new to using kendo

We want to allow user to drag and drop to show/hide columns from a column chooser box.  We want to allow user to be able to drag a column from the list box and drop it in the column header of the grid. So it will be easy for user to design their grid columns layout.  Is there an example to do that?

Please check the attached image for the screenshot about the function we want.

 

Stefan
Telerik team
 answered on 15 Nov 2017
3 answers
288 views

I have a multiselect with serverfiltering set to true. It works fine to filter. Now, when I post the control to my controller, I get the ids and that is fine too. But, when I return to my view with the same set of ids, the multiselect textbox is empty. The ids come back, but there is no select option to show the values. How can I retain the values in multiselect texbox when serverfiltering true and returning to the same view.

 

 

Nencho
Telerik team
 answered on 15 Nov 2017
4 answers
1.9K+ views

I know in my Grid, I can set the Width of the PopUp Edit dialog.  However, the controls inside of that edit window do not seem to care about the width of the window.  For example, here is my Grid code:

@(Html.Kendo().Grid<Provider>()
    .Name("providerGrid")
    .Columns(cols =>
    {
        cols.Bound(c => c.ProviderName);
        cols.Bound(c => c.Active).ClientTemplate("#: Active ? 'Yes' : 'No' #");
        cols.Command(c =>
        {
            c.Edit();
            c.Destroy();
        });
    })
    .DataSource(ds => ds
        .Ajax()
        .Model(m =>
        {
            m.Id(d => d.RecordId);
            m.Field(d => d.ProviderName);
            m.Field(d => d.Active);
        })
        .Update(u => u.Action("UpdateProvider", "Policy"))
        .Read(r => r.Action("GetProviders", "Policy").Type(HttpVerbs.Get))
        .Destroy(d => d.Action("DeleteProvider", "Policy"))
    )
    .Editable(e => e.Mode(GridEditMode.PopUp).TemplateName("ProviderEdit").Window(w => w.Title("Edit Provider").Width(500)))
)

 

But the edit window looks like utter crap now.  See attached image. SO what do I need to do to actually get a decent looking edit dialog in this thing?

The more and more I work with this grid, the more and more I dislike it.  It's basic functionality, out of the box really is quite lame.  The only way to get a decent grid is by overriding everything in it, and I'm so very tired of writing grids...  ARGH!!!  

Sorry about that last bit, just had to vent for a bit...

 

IanV
Top achievements
Rank 1
Veteran
 answered on 15 Nov 2017
2 answers
240 views

Hi,

 We're trying to use foreign key columns in the MVC grid and came to the realization it sorts on the numeric ID value rather than the foreign table text value. Telerik has mentioned there is no way for them to implement a fix, but our group was wondering if anyone else has come up with a work-around or simple fix to accomplish this.

Allan
Top achievements
Rank 1
 answered on 15 Nov 2017
3 answers
209 views

The asp-net mvc example shows how to load a spreadsheet and serialize it.

public class HomeController : Controller
{
    public ActionResult Read()
    {
        var path = Server.MapPath("~/App_Data/path/to/document.xlsx");
        var workbook = Telerik.Web.Spreadsheet.Workbook.Load(path);
        //Uses Newtonsoft.Json internally to serialize fields correctly.
        return Content(workbook.ToJson(), Telerik.Web.Spreadsheet.MimeTypes.JSON);
    }
}

 

Question:

What would the razor code look like to render the serialized workbook sent as the view model ?

Neli
Telerik team
 answered on 14 Nov 2017
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
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
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?