Telerik Forums
UI for ASP.NET MVC Forum
5 answers
320 views

Hi,

I am new to Telerik. I am doing a trial with Telerik Grid using ASP.Net MVC. I couldn't get my grid to display data when the page is loaded. Below are my code blocks:

1. ProductService:

using System;<br>using System.Collections.Generic;<br>using System.Data;<br>using System.Linq;<br>using System.Web;<br>using System.Data.Entity;<br><br>namespace AdmManagerBeta.Models<br>{<br>    public class ProductService : IDisposable<br>    {<br>        private static bool UpdateDatabase = false;<br>        private ADMUsersEntities entities;<br><br>        public ProductService(ADMUsersEntities entities)<br>        {<br>            this.entities = entities;<br>        }<br><br>        public IList<ProductViewModel> GetAll()<br>        {<br>            var result = HttpContext.Current.Session["Products"] as IList<ProductViewModel>;<br><br>            if (result == null || UpdateDatabase)<br>            {<br>                result = entities.Products.Select(product => new ProductViewModel<br>                {<br>                    ProductID = product.ProductID,<br>                    ProductName = product.ProductName<br>                    //UnitPrice = product.UnitPrice.HasValue ? product.UnitPrice.Value : default(decimal),<br>                    //UnitsInStock = product.UnitsInStock.HasValue ? product.UnitsInStock.Value : default(short),<br>                    //QuantityPerUnit = product.QuantityPerUnit,<br>                    //Discontinued = product.Discontinued,<br>                    //UnitsOnOrder = product.UnitsOnOrder.HasValue ? (int)product.UnitsOnOrder.Value : default(int),<br>                    //CategoryID = product.CategoryID,<br>                    //Category = new CategoryViewModel()<br>                    //{<br>                    //    CategoryID = product.Category.CategoryID,<br>                    //    CategoryName = product.Category.CategoryName<br>                    //},<br>                    //LastSupply = DateTime.Today<br>                }).ToList();<br><br>                HttpContext.Current.Session["Products"] = result;<br>            }<br><br>            return result;<br>        }<br><br>        public IEnumerable<ProductViewModel> Read()<br>        {<br>            return GetAll();<br>        }<br><br>        public void Create(ProductViewModel product)<br>        {<br>            if (!UpdateDatabase)<br>            {<br>                var first = GetAll().OrderByDescending(e => e.ProductID).FirstOrDefault();<br>                var id = (first != null) ? first.ProductID : 0;<br><br>                product.ProductID = id + 1;<br><br>                if (product.CategoryID == null)<br>                {<br>                    product.CategoryID = 1;<br>                }<br><br>                if (product.Category == null)<br>                {<br>                    product.Category = new CategoryViewModel() { CategoryID = 1, CategoryName = "Beverages" };<br>                }<br><br>                GetAll().Insert(0, product);<br>            }<br>            else<br>            {<br>                var entity = new Product();<br><br>                entity.ProductName = product.ProductName;<br>                entity.UnitPrice = product.UnitPrice;<br>                entity.UnitsInStock = (short)product.UnitsInStock;<br>                entity.Discontinued = product.Discontinued;<br>                entity.CategoryID = product.CategoryID;<br><br>                if (entity.CategoryID == null)<br>                {<br>                    entity.CategoryID = 1;<br>                }<br><br>                if (product.Category != null)<br>                {<br>                    entity.CategoryID = product.Category.CategoryID;<br>                }<br><br>                entities.Products.Add(entity);<br>                entities.SaveChanges();<br><br>                product.ProductID = entity.ProductID;<br>            }<br>        }<br><br>        public void Update(ProductViewModel product)<br>        {<br>            if (!UpdateDatabase)<br>            {<br>                var target = One(e => e.ProductID == product.ProductID);<br><br>                if (target != null)<br>                {<br>                    target.ProductName = product.ProductName;<br>                    target.UnitPrice = product.UnitPrice;<br>                    target.UnitsInStock = product.UnitsInStock;<br>                    target.Discontinued = product.Discontinued;<br><br>                    if (product.CategoryID == null)<br>                    {<br>                        product.CategoryID = 1;<br>                    }<br><br>                    if (product.Category != null)<br>                    {<br>                        product.CategoryID = product.Category.CategoryID;<br>                    }<br>                    else<br>                    {<br>                        product.Category = new CategoryViewModel()<br>                        {<br>                            CategoryID = (int)product.CategoryID,<br>                            CategoryName = entities.Categories.Where(s => s.CategoryID == product.CategoryID).Select(s => s.CategoryName).First()<br>                        };<br>                    }<br><br>                    target.CategoryID = product.CategoryID;<br>                    target.Category = product.Category;<br>                }<br>            }<br>            else<br>            {<br>                var entity = new Product();<br><br>                entity.ProductID = product.ProductID;<br>                entity.ProductName = product.ProductName;<br>                entity.UnitPrice = product.UnitPrice;<br>                entity.UnitsInStock = (short)product.UnitsInStock;<br>                entity.Discontinued = product.Discontinued;<br>                entity.CategoryID = product.CategoryID;<br><br>                if (product.Category != null)<br>                {<br>                    entity.CategoryID = product.Category.CategoryID;<br>                }<br><br>                entities.Products.Attach(entity);<br>                entities.Entry(entity).State = EntityState.Modified;<br>                entities.SaveChanges();<br>            }<br>        }<br><br>        public void Destroy(ProductViewModel product)<br>        {<br>            if (!UpdateDatabase)<br>            {<br>                var target = GetAll().FirstOrDefault(p => p.ProductID == product.ProductID);<br>                if (target != null)<br>                {<br>                    GetAll().Remove(target);<br>                }<br>            }<br>            else<br>            {<br>                var entity = new Product();<br><br>                entity.ProductID = product.ProductID;<br><br>                entities.Products.Attach(entity);<br><br>                entities.Products.Remove(entity);<br><br>                var orderDetails = entities.Order_Details.Where(pd => pd.ProductID == entity.ProductID);<br><br>                foreach (var orderDetail in orderDetails)<br>                {<br>                    entities.Order_Details.Remove(orderDetail);<br>                }<br><br>                entities.SaveChanges();<br>            }<br>        }<br><br>        public ProductViewModel One(Func<ProductViewModel, bool> predicate)<br>        {<br>            return GetAll().FirstOrDefault(predicate);<br>        }<br><br>        public void Dispose()<br>        {<br>            entities.Dispose();<br>        }<br>    }<br>}

 

2. ProductController.cs:

using AdmManagerBeta.Models;<br>using Kendo.Mvc.Extensions;<br>using Kendo.Mvc.UI;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Mvc;<br><br>namespace AdmManagerBeta.Controllers<br>{<br>    public class ProductController : Controller<br>    {<br>        private ProductService productService;<br><br>        public ProductController()<br>        {<br>            productService = new ProductService(new ADMUsersEntities());<br>        }<br><br>        protected override void Dispose(bool disposing)<br>        {<br>            productService.Dispose();<br><br>            base.Dispose(disposing);<br>        }<br>        public ActionResult Index()<br>        {<br>            return View();<br>        }<br><br>        public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request)<br>        {<br>            return Json(productService.Read().ToDataSourceResult(request));<br>        }<br><br>        [AcceptVerbs(HttpVerbs.Post)]<br>        public ActionResult Editing_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)<br>        {<br>            var results = new List<ProductViewModel>();<br><br>            if (products != null && ModelState.IsValid)<br>            {<br>                foreach (var product in products)<br>                {<br>                    productService.Create(product);<br>                    results.Add(product);<br>                }<br>            }<br><br>            return Json(results.ToDataSourceResult(request, ModelState));<br>        }<br><br>        [AcceptVerbs(HttpVerbs.Post)]<br>        public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)<br>        {<br>            if (products != null && ModelState.IsValid)<br>            {<br>                foreach (var product in products)<br>                {<br>                    productService.Update(product);<br>                }<br>            }<br><br>            return Json(products.ToDataSourceResult(request, ModelState));<br>        }<br><br>        [AcceptVerbs(HttpVerbs.Post)]<br>        public ActionResult Editing_Destroy([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)<br>        {<br>            if (products.Any())<br>            {<br>                foreach (var product in products)<br>                {<br>                    productService.Destroy(product);<br>                }<br>            }<br><br>            return Json(products.ToDataSourceResult(request, ModelState));<br>        }<br>    }<br>}<br>

 

3. Index.cshtml:

@using Kendo.Mvc.UI;<br><br>@(Html.Kendo().Grid<AdmManagerBeta.Models.ProductViewModel>()<br>    .Name("Grid")<br>    .Columns(columns =><br>    {<br>        columns.Bound(p => p.ProductName);<br>        columns.Bound(p => p.UnitPrice).Width(140);<br>        columns.Bound(p => p.UnitsInStock).Width(140);<br>        columns.Bound(p => p.Discontinued).Width(100);<br>        columns.Command(command => command.Destroy()).Width(150);<br>    })<br>    .ToolBar(toolbar =><br>    {<br>        toolbar.Create();<br>        toolbar.Save();<br>    })<br>    .Editable(editable => editable.Mode(GridEditMode.InCell))<br>    .Pageable()<br>    .Navigatable()<br>    .Sortable()<br>    .Scrollable()<br>    .DataSource(dataSource => dataSource<br>        .Ajax()<br>        .Batch(true)<br>        .PageSize(20)<br>        .ServerOperation(false)<br>        .Events(events => events.Error("error_handler"))<br>        .Model(model => model.Id(p => p.ProductID))<br>        .Create("Editing_Create", "Product")<br>        .Read("Editing_Read", "Product")<br>        .Update("Editing_Update", "Product")<br>        .Destroy("Editing_Destroy", "Product")<br>    )<br>)<br><script type="text/javascript"><br>    function error_handler(e) {<br>        if (e.errors) {<br>            var message = "Errors:\n";<br>            $.each(e.errors, function (key, value) {<br>                if ('errors' in value) {<br>                    $.each(value.errors, function() {<br>                        message += this + "\n";<br>                    });<br>                }<br>            });<br>            alert(message);<br>        }<br>    }<br></script>

 

4. _Layout.cshtml:

<p><!DOCTYPE html><br><html><br><head><br>    <title>@ViewBag.Title - My Telerik MVC Application</title><br>    <link href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.common.min.css" rel="stylesheet"><br>    <link href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.metro.min.css" rel="stylesheet"><br>    <link href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.dataviz.min.css" rel="stylesheet"><br>    <link href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.dataviz.metro.min.css" rel="stylesheet"><br>       <link href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" rel="stylesheet" type="text/css" /><br>    <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script><br>  <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jszip.min.js"></script><br>   <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script><br>   <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.aspnetmvc.min.js"></script><br><script src="http://code.jquery.com/jquery-1.8.2.min.js"></script><br>    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /><br>      <script src="@Url.Content("~/Scripts/kendo.modernizr.custom.js")"></script><br></head><br><body><br>    <header><br>        <div class="content-wrapper"><br>            <div class="float-left"><br>                <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p><br>            </div><br>            <div class="float-right"><br>                <nav><br>                    <ul id="menu"><br>                        <li>@Html.ActionLink("Home", "Index", "Home")</li><br>                        <li>@Html.ActionLink("Register", "Index", "Register")</li><br>                        <li>@Html.ActionLink("Login", "Index", "Login")</li><br>                        <li>@Html.ActionLink("Product", "Index", "Product")</li><br>                    </ul><br>                </nav><br>            </div><br>        </div><br>    </header><br>    <div id="body"><br>        @RenderSection("featured", required: false)<br>        <section class="content-wrapper main-content clear-fix"><br>            @RenderBody()<br>        </section><br>    </div><br>    <footer><br>        <div class="content-wrapper"><br>            <div class="float-left"><br>                <p>&copy; @DateTime.Now.Year - My Telerik MVC Application</p><br>            </div><br>        </div><br>    </footer><br></body><br></html></p><p></p><p></p><p></p>

 

 

Stefan
Telerik team
 answered on 29 Nov 2017
3 answers
242 views

Hi,

I am trying to use editor template in grid and for that i have html partial view but i am unable to find the way to send the bounded context to my partial view. can you please help guys ??

 

 

Viktor Tachev
Telerik team
 answered on 29 Nov 2017
3 answers
182 views

Im using .Net 4.5 MVC and Kendo UI release 2017.3.913 with the MVC wrappers.

I have a Kendo scheduler embedded in a Kendo TabStrip and it works fine so far with exception of displaying All Day events.

A single All Day event displays fine however when I create multiple all day events only the first is ever displayed in the All Day row of the scheduler. (see image Scheduler_InTabStrip)

When I moved the exact same Scheduler out of the TabStrip it displays the multiple All Day events fine (see image Scheduler_OutTabStrip). Im not doing anything fancy css wise in the TabStrip but Im  guessing the TabStrip style/css formatting is affecting the Scheduler somehow.

Ruairi
Top achievements
Rank 1
 answered on 29 Nov 2017
15 answers
5.4K+ views
I have declared the following DropDownList

            @(Html.Kendo().DropDownListFor(model => model.CurrencyCode)
                .OptionLabel("Select Currency Code...")
                .Items(items => {
                    items.Add().Text("U.S. Dollars").Value("USD");
                    items.Add().Text("British Pounds").Value("GBP");
                    items.Add().Text("Hong Kong Dollars").Value("HKD");
                    items.Add().Text("Euros").Value("EUR");
                    items.Add().Text("Chinese Yuan").Value("RMB");
                    items.Add().Text("Russian Rubles").Value("RUB");
                })
            )

When an item is first selected, the value is set to [object Object].  However, after the record is saved, the second time it is selected, the value is set to the correct "Value".

Any ideas what may be causing this?
Dimitar
Telerik team
 answered on 29 Nov 2017
3 answers
820 views

I am unable to get my grid to filter on more than 1 column. When I try to add the 2nd filter I get a 500 error because it seems Kendo is trying to make a call to my MVC action without any parameters. I'm getting this behavior on 2 different grid and dataources.

Grid (shortened):

@(Html.Kendo().Grid<FooItemViewModel>()

    .Name("FooGrid")
    .Columns(column =>
    {
        column.Bound(p => p.FooTypeCode).Title("Type").Width(22);
        column.Bound(p => p.FooCode).Title("Foo Code").Width(40);
        column.Bound(p => p.FooDesc).Title("Foo Description").Width(260);
        column.Bound(p => p.ReportCode).Title("Report").Width(20);
    })
    .Filterable()
    .Sortable()
    .Pageable(builder => builder.PageSizes(new[] { 10, 25, 100 }))
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(25)
        .Model(m =>
        {
            m.Id(s => s.FooID);
            m.Field(s => s.FooID).Editable(false);
        })
        .Read(read => read.Action("Read", "Foo"))
        .Create(create => create.Action("Create", "Foo"))
        .Update(update => update.Action("Update", "Foo"))
        .Destroy(update => update.Action("Delete", "Foo"))
        .Events(events => events.Error("onDataSourceError"))
    ))

Controller:

    public JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            var Foos = _db.Foos.Project().To<FooItemViewModel>();
            DataSourceResult response = Foos.ToDataSourceResult(request);
            return Json(response, JsonRequestBehavior.AllowGet);
        }

I have tried adding .ServerOperation(true), but that does not work. When the grid first loads I hit the Read action with empty datasourcerequest as expected. When I add a filter I also hit the server read action with a datasourcerequest and the expected column filter passed in. When I select a 2nd column filter and click "Filter" I get the 500 error in the console because it appears it tries to just call \Foo\Read without any parameters.

I see a "serverFiltering: true" in jquery version, but no equivalent in the MVC wrappers. Any help appreciated.

 

 

Steve
Top achievements
Rank 1
 answered on 28 Nov 2017
3 answers
158 views

I am using the calendar and the scheduler and would like to integrate them so that when the date is selected on the calendar all the "appointments" for that day show on the scheduler next to it.  

It is just a basic calendar and scheduler.

 

 I would like it to look like the attachment

 

 

Plamen
Telerik team
 answered on 28 Nov 2017
2 answers
365 views

When I am using the calendar it is very small and I would like to expand it to fit the entire page width

 

Here is the code I am using:

 

<div style="text-align:center;">
    @(Html.Kendo().Calendar()
.Name("calendar")
)
</div>

 I am not sure if it would be in the css or if I can use the inline styling


Max
Top achievements
Rank 2
 answered on 27 Nov 2017
4 answers
253 views

Hello,

I have an image browser that users are going to be uploading a large number of files to. I'm wondering if it is possible to do one of the following two things to help them manage these images:

1) Sort images shown in the browser by date, rather than name.

2) Automatically select an image on upload. 

Thank you! 

Jackie
Top achievements
Rank 1
 answered on 27 Nov 2017
12 answers
358 views

Hello,

Today I just updated our project to ASP.NET Core 2.0.  It looks like this broke my Kendo grids.  Is this a known problem, if so will it be fixed soon?  The stack trace shows this is happening in the Kendo code.

 

TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.ModelBinding.ValueProviderResultExtensions' from assembly 'Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

David
Top achievements
Rank 1
 answered on 27 Nov 2017
1 answer
1.2K+ views

Hi,

I'm having some trouble with setting a DropDownList value while editing a grid inline.

This is my datasource for the DropDownList:

01.var baseTypesDataSource = new kendo.data.DataSource({
02.    type: "json",
03.    transport: {
04.        read: {
05.            url: "Profile/GetBaseTypes"
06.        }
07.    },
08.    schema: {
09.        model: {
10.            id: "merchandisingBaseTypeId",
11.            fields: {
12.                merchandisingBaseTypeId: { type: "number" },
13.                merchandisingBaseType: { type: "string" }
14.            }
15.        }

 

This is my grid:

01.$("#merchandisingProfileGrid").kendoGrid({
02.    dataSource: profilesDS,
03.    columns: [
04.        { field: "profileNo", title: "Profile No" },
05.        { field: "palletBay", title: "Pallet Bay", editor: booleanEditor, template: kendo.template($("#palletBayTemplate").html()) },
06.        { field: "merchandisingBaseType", title: "Base Type", editor: BaseTypesDropdowns, template: kendo.template($("#baseTypeTemplate").html()) },
07.        { field: "quantity", title: "Overs Qty" },
08.        { field: "comments", title: "Notes" },
09.        { command: ["edit"], width: "200px" }
10.    ],
11.    editable: "inline",
12.    filterable: true
13.});

 

And this is my custom editor for the DropDownList:

01.function BaseTypesDropdowns(container, options) {
02.    $('<input id="bt_' + options.model.id + '" required name="' + options.field + '" />')
03.        .appendTo(container)
04.        .kendoDropDownList({
05.            autoBind: true,
06.            dataTextField: "merchandisingBaseType",
07.            dataValueField: "merchandisingBaseTypeId",
08.            dataSource: baseTypesDataSource,
09.            dataBound: function (e) {
10.                $("#bt_" + options.model.id).data("kendoDropDownList").value(options.model.merchandisingBaseTypeId);
11.            },
12.            change: function (e) {
13.                var dataItem = e.sender.dataItem();
14.                options.model.set("merchandisingBaseTypeId", dataItem.merchandisingBaseTypeId);
15.            }
16.        });
17.}

 

I am simply trying to retain the grid value in the dropdown when I edit a row inline.

The above code does correctly work the first time I edit a row, however on subsequent edits the dropdown loads displaying blank, but has the correct value seelcted when I expand the dropdown (can be seen in the attached image).

Stefan
Telerik team
 answered on 27 Nov 2017
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?