我有使用此控制器的asp net核心应用程序:
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");
}
});
});
答案 0 :(得分: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");
}
});
});
如果您有任何问题,请告诉我
答案 1 :(得分: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");
}
});
});