简体   繁体   English

显示从Asp.Net MVC中的Controller返回的JSON数组数据

[英]Display JSON Array Data Returned from Controller in Asp.Net MVC

I have an action method in my controller as; 我的控制器中有一个动作方法;

public ActionResult IndexWithJson(int Id, int? page)
{
    int pageSize = 2;
    int pageNumber = (page ?? 1);

    using (var adsRepo = new AdvertisementRepository())
    {
        if (Id > 0)
        {
            return Json(new{
                Data = adsRepo.GetAdvertisementBySubCategoryId(Id).ToPagedList(pageNumber, pageSize)
            }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return View("404");
        }

    }
}

the result output in the browser is; 浏览器中的结果输出是; 在此输入图像描述 As you can see in the picture, I have an wrap up the data (in controller as well) with an object called "Data". 正如您在图片中看到的那样,我将数据(在控制器中)与一个名为“Data”的对象进行包装。
Now when I call this using jQuery like this; 现在当我用这样的jQuery调用它时;

var serviceBase = "/catalog/";

$.ajax({
    url: serviceBase + 'IndexWithJson',
    contentType: 'application/json; charset=utf-8',
    dataType:'json',
    data: { Id: categoryId, page: page },
    success: function (data) {
        alert(data.Title);
    }
});

I see null in alert box. 我在警告框中看到null。
What is the problem here? 这里有什么问题?
How do I actually display just one property (see the picture fro properties) in alert box. 如何在警告框中实际显示一个属性(请参阅属性图片)。
Is my dataType attribute right in jQuery ajax function? 我的dataType属性是否在jQuery ajax函数中正确? (I guess it should be JSONP (我想它应该是JSONP

try this: 试试这个:

data.Data[0].Title

This should be working 这应该有效

Try 尝试

alert(data[0].Title)

It's an array. 这是一个阵列。

To display all you could do something like this: 要显示所有你可以做这样的事情:

$.each(data, function(index, value) {
    $('#somediv').append(value.Title);
});

I think you need to use JSON.stringify to send arguments(in your ajax call to controller. Something like 我认为你需要使用JSON.stringify来发送参数(在你的ajax调用中给控制器。有点像
data: JSON.stringify({ Id: categoryId, page: page }), data:JSON.stringify({Id:categoryId,page:page}),
Are you getting Id and page values at controller end properly? 您是否正确地在控制器端获得Id和页面值? I think your result of ajax call is coming as null ie data = null at client end. 我认为你的ajax调用结果是null,即客户端的data = null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM