Cannot get json data with ajax in Razor Pages [duplicate]

邮差的信 提交于 2019-12-24 22:53:42

问题


i am trying to get some data from Razor Pages in ASP.NET Core 2.0.

But the problem is that it does not returns any data. I also tried debugging it, it does not fire that method (OnGetProducts) at all.

The model Index.cshtml.cs:

    private IProductRepository _productRepository;

    public IndexModel(IProductRepository repository)
    {
        _productRepository = repository;
    }

    public void OnGet()
    {

    }

    public IActionResult OnGetProducts(int page)
    {
        var model = _productRepository.GetProducts().Skip(page * 10).Take(10);

        return new JsonResult(model);
    }

the razor page Index.cshtml

<div id="products">
</div>

@section scripts{

<script>
    $(function () {
        getProducts(0);

    });


    var isInitialized = false;

    function getProducts(page) {
        $.ajax({
            type: 'GET',
            url: "Products",
            contentType: "application/json",
            dataType: "json",
            data: {
                handler: 'Products',
                page: page
            },
            success: function (datas) {
                console.log(datas);
            }
        });
    }
</script>

}

p.s. this page in in folder Pages/Products/Index.cshtml(.cs)


回答1:


I usually use razor functions to generate URLs instead of hard coding them in js. If your action is not even being triggered, assuming that you are not accidentally in release mode, it is because the URL doesn't point to the right location. First of all set js variables in razor something like this:

var productsURL = @Url.Context("~/products");

Also run yourdomain/products in your browser and if you get a 404.

Alternatively I use this function to directly use c# objects in js:

public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
   => htmlHelper.Raw(JsonConvert.SerializeObject(obj));

With this function created in a static class, you can also create a js object directly something like this:

<script>
    var products = @Html.ToJS(repository.GetProducts().Skip(page * 10).Take(10));
</script>

Of course this will only create the object in page load, if you want it to change after page load, you can consider creating a partial view via ajax. Also note that the second alternative will be slower than the first for ajax.



来源:https://stackoverflow.com/questions/47610061/cannot-get-json-data-with-ajax-in-razor-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!