Ajax POST方法无法运行asp.net核心

问题描述 投票:0回答:2

我有这个控制器的asp网络核心应用程序:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using NewsletterWebsiteSample.Models;
using Newtonsoft.Json;

namespace NewsletterWebsiteSample.Controllers
{
    public class GalleryController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public GalleryController(IHostingEnvironment he)
        {
            _hostingEnvironment = he;
        }

        [HttpPost]
        public IActionResult GetAll()
        {
            ErrorViewModel em = new ErrorViewModel();
            List<string> list = new List<string>();
            string[] files = Directory.GetFiles(_hostingEnvironment.WebRootPath + "\\Uploads\\Images");
            foreach (string file in files)
                list.Add(Path.GetFileName(file));

            em.Message = JsonConvert.SerializeObject(list);
            return View("Empty", em);
        }
    }
}

当我手动转到那个页面时它工作并返回页面中的json字符串,但是当我尝试从我的js文件中获取它时,我的ajax返回错误。这是我在获取它时使用的代码

$(function () {
    $.ajax({
        type: "POST",
        url: "/Gallery/GetAll",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert("ERROR");
        }
    });
});
ajax asp.net-core asp.net-ajax
2个回答
2
投票

我假设你想以json格式返回文件名列表?所以我会把你的代码改成这个

    [HttpGet]
    public IActionResult GetAll()
    {
        ErrorViewModel em = new ErrorViewModel();
        List<string> list = new List<string>();
        string[] files = Directory.GetFiles(_hostingEnvironment.WebRootPath + "\\Uploads\\Images");
        foreach (string file in files)
            list.Add(Path.GetFileName(file));

        return Json(list);
    }

和你的ajax代码

$(function () {
    $.ajax({
        type: "GET",
        url: "/Gallery/GetAll",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function () {
            alert("ERROR");
        }
    });
});

如果您有任何问题,请告诉我


0
投票

在mvc核心,你不应该说dataType: "json"。请输入:

$(function () {
    $.ajax({
        type: "GET",
        url: "/Gallery/GetAll",
        contentType: "application/json; charset=utf-8",

        success: function (data) {
            console.log(data);
        },
        error: function () {
            alert("ERROR");
        }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.