1

I'm using EF 4. Currently I'm inserting data in two entities through jQuery ajax POST method. Entities looks like:enter image description here

My Web service looks like:

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class AddArea : System.Web.Services.WebService
{
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public Int64 InsertArea(string forestType, byte NumberOfPillars, bool isReferencePoint, decimal AreaCalculated)
    {
        using (var db = new DefaultCS())
        {
            var forestArea = new ForestArea();
            forestArea.ForestType = forestType;
            forestArea.NumberOfPillars = NumberOfPillars;
            forestArea.isReferencePoint = isReferencePoint;
            forestArea.AreaCalculated = AreaCalculated;

            db.ForestAreas.AddObject(forestArea);
            db.SaveChanges();

            return forestArea.Id;
        }
    }

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public string InsertCoordinates(long forestAreaId, string pillarNo, string latitude, string longitude, string forwardBearings, string backBearings, decimal backDistanceInMeter, decimal backDistanceInChain)
    {
        using (var db = new DefaultCS())
        {
            ForestCoordinate forestCoordinates = new ForestCoordinate();
            forestCoordinates.ForestAreaId = forestAreaId;
            forestCoordinates.PillarNo = pillarNo;
            forestCoordinates.Latitude = latitude;
            forestCoordinates.Longitude = longitude;
            forestCoordinates.ForwardBearings = forwardBearings;
            forestCoordinates.BackBearings = backBearings;
            forestCoordinates.BackDistanceInMeter = backDistanceInMeter;
            forestCoordinates.BackDistanceInChain = backDistanceInChain;

            db.ForestCoordinates.AddObject(forestCoordinates);
            db.SaveChanges();
        }
        return "true";
    }
}

The InserArea methods runs one time but 'InsertCoordinates` run in loop. here is my ajax:

$.ajax({
    type: "POST",
    url: "AddArea.asmx/InsertArea",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: '{ "forestType": "R", "NumberOfPillars": "' + (parseInt($('#txtNoPillar').val()) + 1) + '", "isReferencePoint": "' + $('#rdReference').is(':checked') + '", "AreaCalculated": "' + $('#areaM').text() + '" }',
    success: function (response) {
        var areaId = response.d;
        var numOfPillar = $('#txtNoPillar').val();
        var i = 0;
        for (i; i <= numOfPillar; i++) {

            $.ajax({
                type: "POST",
                url: "AddArea.asmx/InsertCoordinates",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{ "forestAreaId": "' + areaId + '", "pillarNo": "' + $('#txtPillarNo' + i).val() + '", "latitude": "' + $('#txtLatitude' + i).val() + '", "longitude": "' + $('#txtLongitude' + i).val() + '", "forwardBearings": "' + $('#txtBearing' + i).val() + '", "backBearings": "' + $('#txtBackBearing' + i).val() + '", "backDistanceInMeter": "' + $('#txtDistance' + i).val() + '", "backDistanceInChain": "' + $('#txtDistanceInChain' + i).val() + '" }',
                success: function (response) {
                    console.log(response);
                },
                error: function (response) {
                    console.log(response);
                }
            });
        }
        console.log(response);
    },
    error: function (response) {
        console.log(response);
    }
}).done(function () {
    alert("Data saved successfully.");
});

My Question: Is there any way to eliminate looping of InsertCoordinates method and post Collection of Entity(ForestCoordinate) at one time to web service? This is working correctly but I want more elegance way to do this. Thanks for any help.

Update 1 Here is new webservice according to @Eugene P.

[WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public Int64 InsertArea(ForestArea forestArea, EntityCollection<ForestCoordinate> forestCoordinates)
    {
        using (var db = new DefaultCS())
        {
            forestArea.ForestCoordinates = forestCoordinates;
            db.ForestAreas.AddObject(forestArea);
            db.SaveChanges();

            return forestArea.Id;
        }
    }

and jQuery is :

var forestArea = {};

                forestArea.forestType = "R";
                forestArea.NumberOfPillars = (parseInt($('#txtNoPillar').val()) + 1);
                forestArea.isReferencePoint = $('#rdReference').is(':checked');
                forestArea.AreaCalculated = $('#areaM').text();

                var json = { "forestCoordinates": [] };
                var numOfPillar = $('#txtNoPillar').val();
                var i = 0;
                for (i; i <= numOfPillar; i++) {

                    json.forestCoordinates.push({ pillarNo: $('#txtPillarNo' + i).val(), latitude: $('#txtLatitude' + i).val(), longitude: $('#txtLongitude' + i).val(), forwardBearings: $('#txtBearing' + i).val(), backBearings: $('#txtBackBearing' + i).val(), backDistanceInMeter: $('#txtDistance' + i).val(), backDistanceInChain: $('#txtDistanceInChain' + i).val() });
                }

                // Create a data transfer object (DTO) with the proper structure.
                var DTO = { 'forestArea': forestArea, 'forestCoordinates': json };
                $.ajax({
                    type: "POST",
                    url: "AddArea.asmx/InsertArea",
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    data: JSON.stringify(DTO),
                    success: function (response) {
                        var areaId = response.d;
                        console.log(response);
                    },
                    error: function (response) {
                        console.log(response);
                    }
                }).done(function () {
                    alert("Data saved successfully.");
                });

At the client side json object shows non-empty array but at server it is always zero. What wrong is going?

صفي
  • 1,068
  • 2
  • 15
  • 34

1 Answers1

3

Yes. it's possible to hugely reduce your code.

Despite on the case that ASMX to old already . it does support collections as a parameter of exposed operation.

quick sample :

server side:

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(Ent[] entities)
        {
            return "Hello World";
        }


        public class Ent
        {
            public string Name { get; set; }    
        }
    }

client :

$(function () {
            var json = { "entities": [] };
            json.entities.push({ Name: "name1" });
            json.entities.push({ Name: "name2" });
            json.entities.push({ Name: "name3" });
            $.ajax({
                type: "POST",
                url: "/Services/WebService1.asmx/HelloWorld",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data:  JSON.stringify(json),
                success: function(response) {
                    console.log(response);
                },
                error: function(response) {
                    console.log(response);
                }
            });
        });

some useful links:

  1. here
  2. here
  3. and here
Community
  • 1
  • 1
Eugene P.
  • 2,645
  • 19
  • 23
  • Thanks @Eugene, but I've `EntityCollection forestCoordinates` type to post. Please see update for new webservice. or should I post array and loop into webservice? – صفي Feb 05 '14 at 06:46