Click here to Skip to main content
15,881,836 members
Articles / Web Development / HTML
Tip/Trick

MVC and jQuery with WCF Data Service

Rate me:
Please Sign up or sign in to vote.
4.94/5 (18 votes)
4 Sep 2014CPOL2 min read 59.6K   1.7K   32   7
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:

Image 1

02. Select Model Type:

Image 2

03. Select connection and define the connection name:

Image 3

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

Image 4

05. It will look like this:

Image 5

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:

Image 6

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

Image 7

03.Show like this service:

Image 8

  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.
    C#
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;

    Expose the data which version under ODATA protocol.

Controller

C#
    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

C#
$(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

C#
$(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

C#
$(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

C#
$(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:

Image 9

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) PanSoftware
Australia Australia
I work as a Senior Software Engineer. So I'm Following .Net,ASP.net.ADO.net,MVC.net,Web API,WCF and WCF Data service,Entity framework, java-script, Jquery and Angular framework.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 130730197-Oct-21 15:51
Member 130730197-Oct-21 15:51 
QuestionMissing route config / no actual ODATA suppport... Pin
Member 377822623-Jun-15 14:26
Member 377822623-Jun-15 14:26 
Questionwhere is the route config Pin
cuizhan11-Sep-14 22:52
cuizhan11-Sep-14 22:52 
GeneralMy vote of 5 Pin
Volynsky Alex7-Sep-14 10:56
professionalVolynsky Alex7-Sep-14 10:56 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun4-Sep-14 19:45
Humayun Kabir Mamun4-Sep-14 19:45 
QuestionNot an article Pin
Rage5-Jun-14 0:50
professionalRage5-Jun-14 0:50 
Questionpictures not displayed Pin
fredatcodeproject4-Jun-14 23:14
professionalfredatcodeproject4-Jun-14 23:14 

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

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