将数据从ASp.NET MVC Controller传递到JavaScript函数

Mag*_*age 3 javascript asp.net-mvc jquery

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

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

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

            return coordinateList;

        }
Run Code Online (Sandbox Code Playgroud)

在我的网页中,我有一个JavaScript函数,它接受2个参数并在页面上显示坐标(在地图上)

function GetLocation(y, x){
//my code here
}
Run Code Online (Sandbox Code Playgroud)

我想从我的控制器获取coordiates列表,并将它们传递给JS函数进行处理.

最好的方法是什么?

我尝试使用以下,但我不知道如何解析结果

 $.ajax({
            url: '@Url.Action("GetCoordinate")',
            type: 'GET',
             dataType: 'xml',
            success: function(result) {

            },
            error: function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);}
        });
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Dis*_*ile 8

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

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

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

    return Json(coordinateList, JsonRequestBehavior.AllowGet);

 }
Run Code Online (Sandbox Code Playgroud)

现在你的控制器动作正在返回jQuery可以处理的JSON.

更改您的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);
    }
});
Run Code Online (Sandbox Code Playgroud)

现在你的AJAX方法知道它正在处理JSON数据.你可以使用jQuery的每个方法对数据做一些事情(在这种情况下我只是做一个警报).