ASP.NET MVC Grid Data Not Displayed

6 posts, 1 answers
  1. COLIN
    COLIN avatar
    3 posts
    Member since:
    Nov 2017

    Posted 21 Nov Link to this post

    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>

     

     

  2. Answer
    Stefan
    Admin
    Stefan avatar
    1394 posts

    Posted 23 Nov Link to this post

    Hello, Colin,

    Thank you for the provided project.

    The issue occurs because jQuery was included twice on the page:


    Please include it only once:

    https://docs.telerik.com/kendo-ui/troubleshoot/troubleshooting-common-issues#widgets-are-unavailable-or-undefined

    I hope this is helpful.

    Regards,
    Stefan
    Progress Telerik
    Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
  3. COLIN
    COLIN avatar
    3 posts
    Member since:
    Nov 2017

    Posted 23 Nov in reply to Stefan Link to this post

    Thanks Stefan, it works.

    One more question, I try to update or create new record, but the data is not saved to the underlying database. Is there anything I am not doing right in the controller or the service class?

    Thanks again.

    Colin

  4. Stefan
    Admin
    Stefan avatar
    1394 posts

    Posted 24 Nov Link to this post

    Hello, Colin,
     
    The configuration looks good.

    I compare it with our demo which is used for reference and they are completely identical. The only difference that I can see is that the DbSet is virtual in the provided application and it is just public(no virtual):

    public DbSet<Product> Products { get; set; }

    If the issue still occurs, please provide a fully runnable example with the database, so we can inspect it further.

    Regards,
    Stefan
    Progress Telerik
    Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
  5. COLIN
    COLIN avatar
    3 posts
    Member since:
    Nov 2017

    Posted 27 Nov in reply to Stefan Link to this post

    Hi Stefan,

    Take away the virtual keyword still doesn't work.

    I have attached here the complete workable code. Run the project and click on Product. I have not included the packages folder and bin folder, because the file size will be big. I am using the 2017.3.1026.545.Trial version of Kendon.Mvc.UI. I am suing the standard Northwind database.

    Try changing the product name and click Save. The stop the project and load again. The change made is not saved to DB.

    cheers,

    Colin

  6. Stefan
    Admin
    Stefan avatar
    1394 posts

    Posted 29 Nov Link to this post

    Hello, Colin,

    Thank you for providing the details and the example.

    After researching I noticed that for a demo purpose we are only adding the records to the "HttpContext.Current.Session" to ensure that inappropriate records will not be added to the database where everyone can see them.

    I can suggest checking the following project where we are demonstrating how to add the records in the actual database:

    https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/grid/ajax-editing

    Regards,
    Stefan
    Progress Telerik
    Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Back to Top