从ASP.NET MVC控制器传递数据到JavaScript函数

4

我有一个ASP.NET MVC3应用程序,从WCF服务获取坐标列表。该服务返回一个包含一些属性(Xcoor和Ycoor)的列表。

   public List<Location> GetCoordinate()
        {
            sensor = new Location();

            List<Location> coordinateList = sensor.GetSensorInformation();

            return coordinateList;

        }

在我的网页中,我有一个JavaScript函数,它接受两个参数并在页面上(地图上)显示坐标。
function GetLocation(y, x){
//my code here
}

我希望从我的控制器中获取坐标列表,并将它们传递给该JS函数进行处理。如何最好地实现这一点?我尝试使用以下代码,但不知道如何解析结果:
 $.ajax({
            url: '@Url.Action("GetCoordinate")',
            type: 'GET',
             dataType: 'xml',
            success: function(result) {

            },
            error: function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);}
        });

有什么想法吗?


1
如果GetCoordinatesArray返回一个List<T>,那么jQuery的$.ajax如何将其作为URL调用? - Only Bolivian Here
Sergio,我的错字。我更新了帖子。谢谢。假设我得到了成功访问并且函数(结果)。@Travis,我如何使用JSON来实现这个? - Mage
2个回答

8

将您的控制器更改为以下内容:

public ActionResult GetCoordinate()
{
    sensor = new Location();

    List<Location> coordinateList = sensor.GetSensorInformation();

    return Json(coordinateList, JsonRequestBehavior.AllowGet);

 }

现在你的控制器动作正在返回JSON,jQuery可以处理它。
将你的jQuery方法更改为这样:
$.ajax({
    url: '@Url.Action("GetCoordinate")',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        // process the data coming back
        $.each(data, function(index, item) {
            alert(item);
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

现在你的AJAX方法知道它正在处理JSON数据。您可以使用jQuery each方法对数据进行操作(在此示例中仅做警告)。


"item" 返回对象 Object。如何从列表中获取实际数据? - Mage
好的,我看到数据了...谢谢。我会把那个变量传入我的JS函数中。 - Mage

0

这里有许多东西。

在你的控制器上定义一个函数,定义一个方法

public JsonResult GetCoodinates() { }

在该方法中使用WCF服务器并将结果转换为JsonResult。

在你的JavaScript代码中

$.ajax({ url: '/controller/GetCoordinates', type: GET, dataType: 'json', success: function(data) { $.each(data, function (key, value) { //在这里执行您要进行的调用以将坐标放置在地图上 } });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接