Click here to Skip to main content
Click here to Skip to main content

MVC and jQuery with WCF Data Service

, 4 Sep 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chathuranga Muthukumarana
Software Developer
Sri Lanka Sri Lanka
I'm work as a Software Enginner. So I'm Following .Net,ASP.net.ADO.net,MVC.net,Entity framework.

Comments and Discussions

 
Questionwhere is the route config Pinmembercuizhan11-Sep-14 22:52 
GeneralMy vote of 5 PinprofessionalVolynsky Alex7-Sep-14 10:56 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun4-Sep-14 19:45 
QuestionNot an article PinprofessionalRage5-Jun-14 0:50 
If you remove screenshots and code, there is no content anymore, so this is not an article.
~RaGE();

I think words like 'destiny' are a way of trying to find order where none exists. - Christian Graus
Entropy isn't what it used to.

Questionpictures not displayed Pinmemberfredatcodeproject4-Jun-14 23:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 5 Sep 2014
Article Copyright 2014 by Chathuranga Muthukumarana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid