This is a migrated thread and some comments may be shown as answers.

CRUD Application with Kendo Ui Grid in Asp.net MVC3

0 Answers 420 Views
Grid
This is a migrated thread and some comments may be shown as answers.
mojam
Top achievements
Rank 1
mojam asked on 31 Dec 2012, 05:45 AM
Hello experts
I am new in asp.net mvc and I need to Use Kendo UI grid for one of my CRUD Application. By following https://github.com/telerik/kendo-examples-asp-net-mvc Links project I tried to created a sample project. But when I run this project I doesn't show me any grid control. It only shows me following Lines:

Kendo Grid boud to ASP.NET MVC action methods.

The image of the page look like below

So I failed to operate any crud(create/read/update/delete) operation in my sample project.
For your kind information I am giving my code samples below
DB Context Class
==============
public class DMSContext:DbContext
    {
        public DMSContext() : base("DefaultConnection") { }
        public DbSet<MachineCategory> MachineCats { get; set; }
        public DbSet<clsProducts> Products { get; set; }
       
    }

Model Class
==============
 public class clsProducts
    {
        int productID;
        [Key]
        public int ProductID
        {
            get { return productID; }
            set { productID = value; }
        }
        string  productName, quantityPerUnit;

        public string  QuantityPerUnit
        {
            get { return quantityPerUnit; }
            set { quantityPerUnit = value; }
        }

        public string  ProductName
        {
            get { return productName; }
            set { productName = value; }
        }
        decimal ? unitPrice;

        public decimal ? UnitPrice
        {
            get { return unitPrice; }
            set { unitPrice = value; }
        }
        Int16 ? unitsInStock, unitsOnOrder, reorderLevel;

        public Int16 ? ReorderLevel
        {
            get { return reorderLevel; }
            set { reorderLevel = value; }
        }

        public Int16? UnitsOnOrder
        {
            get { return unitsOnOrder; }
            set { unitsOnOrder = value; }
        }

        public Int16? UnitsInStock
        {
            get { return unitsInStock; }
            set { unitsInStock = value; }
        }
        bool  discontinued;

        public bool Discontinued
        {
            get { return discontinued; }
            set { discontinued = value; }
        }
    }
Controller Class
==============
public class ProductsController : Controller
    {
        private DMSContext db = new DMSContext();
        private iProducts irepository;
       
        public ProductsController()
        {
            this.irepository = new ProductsRepository(new DMSContext());
        }
            
            
            
        //
        // GET: /Products/

        public ViewResult Index()
        {
            //return View(db.Products.ToList());
        var product = from s in irepository.GetProducts()
                          select s;
           return View(product.ToList());
           // return View();
            
        }

        //
        // GET: /Products/Details/5
        [HttpPost]
        public ActionResult Details(int id, int take, int skip, IEnumerable<Sort> sort, Filter filter)
        {
           // clsProducts clsproducts = db.Products.Find(id);
         //   return View(clsproducts);

            var result = irepository.GetProducts()
                   .OrderBy(p => p.ProductID) // EF requires ordered IQueryable in order to do paging
                // Use a view model to avoid serializing internal Entity Framework properties as JSON
                   .Select(p => new clsProducts
                   {
                       ProductID = p.ProductID,
                       ProductName = p.ProductName,
                       UnitPrice = p.UnitPrice,
                       UnitsInStock = p.UnitsInStock,
                       Discontinued = p.Discontinued
                   }).ToList();
                  //.ToDataSourceResult(take, skip, sort, filter);

            return Json(result);



        }

        //
        // GET: /Products/Create

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

        //
        // POST: /Products/Create

        [HttpPost]
        public ActionResult Create(clsProducts clsproducts)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(clsproducts);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(clsproducts);
        }
        
        //
        // GET: /Products/Edit/5
 
        public ActionResult Edit(int id)
        {
            clsProducts clsproducts = db.Products.Find(id);
            return View(clsproducts);
        }

        //
        // POST: /Products/Edit/5

        [HttpPost]
        public ActionResult Edit(clsProducts clsproducts)
        {
            if (ModelState.IsValid)
            {
                db.Entry(clsproducts).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(clsproducts);
        }

        //
        // GET: /Products/Delete/5
 
        public ActionResult Delete(int id)
        {
            clsProducts clsproducts = db.Products.Find(id);
            return View(clsproducts);
        }

        //
        // POST: /Products/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            clsProducts clsproducts = db.Products.Find(id);
            db.Products.Remove(clsproducts);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

       /* protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }*/
    }
Repository Interface
================
 interface iProducts
    {
        IEnumerable<clsProducts> GetProducts();
        clsProducts GetProductsByID(int id);
        void InsertProducts(clsProducts cls);
        void DeleteProducts(int id);
        void UpdateProducts(clsProducts cls);
        void Save(clsProducts cls);
    }

Repositoy Class
================
 public class ProductsRepository : iProducts, IDisposable
    {
        private DMSContext context;
        public ProductsRepository(DMSContext context)
        {
            this.context = context;
        }

        public IEnumerable<clsProducts> GetProducts()
        {
            var query = context.Database.SqlQuery<clsProducts>("populate_products");
            return query.ToList();
        }
        public clsProducts GetProductsByID(int id)
        {
            var query = context.Database.SqlQuery<clsProducts>("populate_products_by_id " + id);
           return query.SingleOrDefault();
        }
        public void DeleteProducts(int catID)
        {
            var query = context.Database.ExecuteSqlCommand("delete_products " + catID);

        }

        public void InsertProducts(clsProducts iMachineCategory)
        {
            //context.MachineCats.Add(iMachineCategory);
            iMachineCategory.ProductID = 0;
            Save(iMachineCategory);
        }

        public void UpdateProducts(clsProducts iMachineCategory)
        {
            
            Save(iMachineCategory);
            context.Entry(iMachineCategory).State = EntityState.Modified;

        }
        public void Save(clsProducts iMachineCategory)
        {
            //context.SaveChanges();
            DMS.Utilities.clsUtility icls = new Utilities.clsUtility();
            context.Database.ExecuteSqlCommand("insert_update_products " + iMachineCategory.ProductID + ",'" + icls.utl_Esc_Single_Quote_Single_Line(iMachineCategory.ProductName) + "'," + icls.utl_Convert_Null_To_Zero(iMachineCategory.UnitPrice.ToString()) + "," + icls.utl_Convert_Null_To_Zero(iMachineCategory.UnitsInStock.ToString()) + "," + icls.utl_convert_Boolean_To_Bit(iMachineCategory.Discontinued));
        }

        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

View
===============
@model IEnumerable<DMS.Models.clsProducts>

@section HeaderSection {
    
    <link href="@Url.Content("~/Content/Kendo/kendo.common.css")" rel="stylesheet"/>
<link href="@Url.Content("~/Content/Kendo/kendo.default.css")" rel="stylesheet"/>
<script src="@Url.Content("~/Scripts/Kendo/kendo.all.js")" type="text/javascript"></script>

   
    

}
<!--http://www.codeproject.com/Articles/277576/AJAX-based-CRUD-tables-using-ASP-NET-MVC-3-and-jTa-->
<h2>Kendo Grid boud to ASP.NET MVC action methods</h2>
@* The DIV where the Kendo grid will be initialized *@
<div id="grid"></div>


<script>
    $(function () {
        $("#grid").kendoGrid({
            height: 400,
            columns: [
                "ProductName",
                { field: "UnitPrice", format: "{0:c}", width: "150px" },
                { field: "UnitsInStock", width: "150px" },
                { field: "Discontinued", width: "100px" },
                { command: "destroy", title: "Delete", width: "110px" }
            ],
            editable: true, // enable editing
            pageable: true,
            sortable: true,
            filterable: true,
            toolbar: ["create", "save", "cancel"], // specify toolbar commands
            dataSource: {
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true,
                pageSize: 10,
                schema: {
                    data: "Data",
                    total: "Total",
                    model: { // define the model of the data source. Required for validation and property types.
                        id: "ProductID",
                        fields: {
                            ProductID: { editable: false, nullable: true },
                            ProductName: { validation: { required: true } },
                            UnitPrice: { type: "number", validation: { required: true, min: 1 } },
                            Discontinued: { type: "boolean" },
                            UnitsInStock: { type: "number", validation: { min: 0, required: true } }
                        }
                    }
                },
                batch: true, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
                transport: {
                    create: {
                        url: "@Url.Action("Create", "Products")", //specify the URL which should create new records. This is the Create method of the HomeController.
                    type: "POST" //use HTTP POST request as the default GET is not allowed for ASMX
                },
                read: {
                    url: "@Url.Action("Index", "Products")", //specify the URL which should return the records. This is the Read method of the HomeController.
                    contentType: "application/json",
                    type: "POST" //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
                },
                update: {
                    url: "@Url.Action("Update", "Products")", //specify the URL which should update the records. This is the Update method of the HomeController.
                    type: "POST" //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
                },
                destroy: {
                    url: "@Url.Action("Delete", "Products")", //specify the URL which should destroy the records. This is the Destroy method of the HomeController.
                    type: "POST" //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
                },
                parameterMap: function (data, operation) {
                    if (operation != "read") {
                        // post the products so the ASP.NET DefaultModelBinder will understand them:

                        // products[0].Name="name"
                        // products[0].ProductID =1
                        // products[1].Name="name"
                        // products[1].ProductID =1

                        var result = {};

                        for (var i = 0; i < data.models.length; i++) {
                            var product = data.models[i];

                            for (var member in product) {
                                result["products[" + i + "]." + member] = product[member];
                            }
                        }

                        return result;
                    } else {
                        return JSON.stringify(data)
                    }
                }
            }
        }
    });
});
</script>

WebConfig
=========
<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

And my database Script is attached below.

If anybody fix my problem it will be great helpful for me.

Thanks in advance
Md. Mojammel Haque
Software Engineer
DIRD Group
E-mail : mojamcpds@gmail.com
Contact: +8801817045882

No answers yet. Maybe you can help?

Tags
Grid
Asked by
mojam
Top achievements
Rank 1
Share this question
or