1
votes


I'm developing a web page that display open street map and gets data from SQL server database by long and lat coordinates i use asp.net mvc and give me this wrong

Uncaught TypeError: Cannot read property 'Name' of undefined
where i bind data from database by javascript


Model
this model data i create GetMap() that return data from database by Json function

  [HttpPost]
        public JsonResult GetMap()
        {
            var data1 =(from p in db.Map
                    select new
                    {
                        Name = p.Name,
                        Latitude = p.Latitude,
                        Logitude = p.Logitude,
                        Location = p.Location,
                        Description = p.Description,
                        Id = p.Id
                    }).ToList().Select(res => new Map
                    {
                        Name = res.Name,
                        Latitude = res.Latitude,
                        Logitude = res.Logitude,
                        Location = res.Location,
                        Description = res.Description,
                        Id = res.Id


                    });
            return Json(data1, JsonRequestBehavior.AllowGet);
        } 
</pre> 

view file
view file that display map and return data by Json function

    <div id="mapid" style="height:600px"></div>
    <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {

        var map = L.map('mapid').setView([31.291340, 34.244190], 13);

        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);





            $.ajax({
                type: "POST",
                url: '/Maps/GetMap',
                success: function (data) {
                    var result = JSON.stringify(data);

                    for (var i = 0; i < result.length; ++i) {

                        var popup =
                            '<b>Name:</b> ' + data[i].Name +
                         '<br/><b>Latitude:</b> ' + data[i].Latitude +
                           '<br/><b>Longitude:</b> ' + data[i].Logitude +
                        '<br/><b>Location:</b> ' + data[i].Location;


                        L.marker([data[i].Latitude, data[i].Logitude])
                            .bindPopup(popup)
                           .addTo(map); 

                    }

                },
                error: function (xhr) {

                    console.log(xhr.responseText);
                    alert("Error has occurred..");
                }
            });
        });

    </script>

3
Check the for loop in your success function, iterating up to result.length but result should be data. The error message indicates that some data[i] is undefined.James
try $.parseJSON(); also check what you get for dataRohitS
What's happening in your linq query though? You can remove the Select part after the .ToList(). And, if those are the only properties in the Map object, you might as well get rid of the entire query and just do return Json(db.Map.ToList())adiga
It is working for you my answer ?Mihai Alexandru-Ionut

3 Answers

2
votes

The issue is in these lines:

 var result = JSON.stringify(data);
 for (var i = 0; i < result.length; ++i) {

JSON.stringify() turns a javascript object to json text and stores it in a string.

You don't need to iterate a json string because you need to iterate a collection.

You have to iterate data directly.

 for (var i = 0; i < data.length; i++) {}

The response of the POST method is parsed automatically by ajax success callback.

Also, you do not need JsonRequestBehavior.AllowGet property when you're doing a POST request. This is required only for GET verb because it protects you against a very specific attack involving JSON requests.

1
votes

You are generating a string here

var result = JSON.stringify(data);

Then looping until the string length, which is the number of characters in this string ( not your json array length)

for (var i = 0; i < result.length; ++i) { }

The string length will be more than your json array length.

So simply fix your loop to use correct variable.

for (var i = 0; i < data.length; ++i) {

}

Also there is no need to call Json.stringify. simply loop through the json array.

Alternatively, you may use $.each

success: function (data) {
  $.each(data,function(indx,item)
  {
    console.log(item.Name);
  }
}

Also your server code could be simplifed. There is no need to do the projection twice.

[HttpPost]
public JsonResult GetMap()
{
        var data1 =db.Map.Select(res => new Map
                              {
                                Name = res.Name,
                                Latitude = res.Latitude,
                                Logitude = res.Logitude,
                                Location = res.Location,
                                Description = res.Description,
                                Id = res.Id
                             }).ToList();
    return Json(data1);
} 

You do not need to specify JsonRequestBehavior.AllowGet when your action method is decorated with [HttpPost]

0
votes

This error means that you are trying to reference a field (Name) which does not exist on a given object (undefined). There are three places in your code which reference a Name field:

  • p.Name
  • res.Name
  • data[i].Name

So one of p, res or data[i] is undefined at the moment that you try to reference the Name property.