Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC and jQuery with WCF Data Service

0.00/5 (No votes)
4 Sep 2014 1  
MVC and jQuery with WCF Data Service

Introduction

In this tip, you can learn about how to use WCF data Service (ODATA) with MVC and jQuery.
I have defined CRUD operations using a model class to use it in jQuery at client side and MVC controller.

Model

First of all, we have to create a simple model. We can have two approaches to creating a model. Those are Code First and Database First. I think we can develop the model easily using database first approach.

01. Select the ADO.NET Entity Data Model:

02. Select Model Type:

03. Select connection and define the connection name:

04. Select the wanted table. If you have views and stored procedures, you can have select them together:

05. It will look like this:

OData

The OData protocol is such as https ATOMPub and JSON. That one also exposes the web resource to outside the OData protocol developed by the Microsoft. One of the benefits of OData is a consistent query experience, defined in the protocol, that enables rich querying using URI query string parameters.

This means I might be able to write a query like this, because of this the queryble string :

http://foo.com/odata/foocat?$filter=fooName
What is the most important part of ODATA protocol?

The important thing is we can filter the data using the Query String.

What is a WCF Data Service

WCF data service was developed by Microsoft. When we are developing the service given the template from Visual Studio tool. That service is built on the REST Service. The developer just needs to configure the data source and let the service template know what data needs to exposed and with what permissions.

Why we are using the WCF data service

When we are developing MVC project, you have to expose some data so you can use WCF data service technology (as well as you can use WEB API).

How to create a WCFDataService

01.Add new Item:

02.Select the WCFDataService item an add (I've installed the 5.3 version don't consider about that):

03.Show like this service:

  1. Set your data sources class
  2. Set to permission to each entities and operation, by default access deny all entities and operation.
    • When use " * " mark allocate the permission to all entities.
    • As well as we can have use the permission for particular entity.
    • Set to permission for all operation.
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;

    Expose the data which version under ODATA protocol.

Controller

        private DemoServiceReference.DemoDatabaseEntities DataContext = null;
        public DemoServiceReference.DemoDatabaseEntities DemoDataContext
        {
            get
            {
               DataContext = new  DemoServiceReference.DemoDatabaseEntities
               (new Uri("http://localhost:2127/Services/DemoWcfDataService.svc/"));
               return DataContext;
            }
            set { DataContext = value; }
        }
         

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

      
       [HttpPost]  
        public ActionResult Details(int id)
        {
            JsonResult result=new JsonResult();
            result.Data = DemoDataContext.DemoTables.ToList();
            return result;
        }

       
        [HttpPost]   
        public ActionResult Create(DemoServiceReference.DemoTable Tables)
        {
            try
            {
                DemoServiceReference.DemoTable objDemoTable = new DemoServiceReference.DemoTable();
                objDemoTable.Name = Tables.Name;
                objDemoTable.Address = Tables.Address;
                DemoDataContext.AddToDemoTables(objDemoTable);
                DemoDataContext.SaveChanges();
                return View();
            }
            catch
            {
                return View();
            }
        }
     
       [HttpPost]
        public ActionResult Edit(DemoServiceReference.DemoTable Tables)
        {
            try
            {
                var objDemoTable = DemoDataContext.DemoTables.Where(x => x.Id == Tables.Id).Single();
                 
                objDemoTable.Name = Tables.Name;
                objDemoTable.Address = Tables.Address;
                DemoDataContext.UpdateObject(objDemoTable);
                DemoDataContext.SaveChanges();
                return View();
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                var objTable = DemoDataContext.DemoTables.Where(x => x.Id == id);
                DemoDataContext.DeleteObject(objTable);
                DemoDataContext.SaveChanges();
                return View();
            }
            catch
            {
                return View();
            }
        }
    }

View

Actually, this one has been written using object oriented concept. Because of that, we can define like entities (client side entries and object name should be match to server side entries and object name).

Create

   $(document).ready(function () {
        $("#btnCreate").click(function () {
            var Tables = {};
           
            Tables.Name = $("#txtName").val();
            Tables.Address = $("#txtAddress").val();
            $.post("/Demo/Create/", Tables, function (data) {

            }, "JSON").success(function () { alert("success"); });

        });
    });

Read

$(document).ready(function () {
        $("#btnDetails").click(function () {
             $.post("/Demo/Details/", {}, function (data) {
                var items = '<table id="tbl"><tr><th style=display:none;>ID</th><th>Name</th><th>Address</th><th>Button</th></tr>';

                $.each(data, function (i, item) {
                    //I don't need to display the ID there fore that on has been hidden.(It's like hidden field.)
                    items += "<tr><td style='display:none';>" + data[i].Id + "</td><td>" + data[i].Name + "</td><td>" + data[i].Address + "</td>";
                    items += "<td> <a href='' class='edit'>Edit</a></td></tr>";
                    //I've used the "class='edit'" this one use for identify the each recode uniquely.
                });
                items += "</table>";
                $('#Result').html(items);

            }, "JSON");
       });

     });

Update

$(document).ready(function () {
        $("#btnEdit").click(function () {
            var Tables = {};
            Tables.Id = $("#txtId").val();
            Tables.Name = $("#txtName").val();
            Tables.Address = $("#txtAddress").val();
            $.post("/Demo/Edit/", Tables, function (data) {

            }, "JSON").success(function () { alert("success"); });
          
        });
    });

//"$(document).on" use for uniquely identyfied the rows on tables
   $(document).on('click', 'td a.edit', function () {
        get_data($(this).parents('tr'));
        return false;
    });
 
 //get data each rows according to selected row.
   function get_data(row) {
        var  _ID = $(row.children().get(0)).text();
             _Name = $(row.children().get(1)).text(),
             _Address = $(row.children().get(2)).text(), 
            
             $("#txtName").val(_Name);
             $("#txtAddress").val(_Address);
             $("#txtId").val(_ID);
             $("#DetailsTabls").show(1000);
    }

Delete

 $(document).ready(function () {
        $("#btnDelete").click(function () {

            var Id = $("#txtId").val();
            $.post("/Demo/Delete/", { id: Id }, function (data) {

            }, "JSON").success(function () { alert("success"); });

        });
    });

This development architecture is very useful for distributed MVC architecture:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here