【发布时间】:2019-09-17 21:15:03
【问题描述】:
我有这个控制器的 asp net core 应用程序:
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");
}
});
});
【问题讨论】:
-
我不明白。您的网址是 GetAll 但您的操作方法是 Post ?你也返回视图?
-
好吧,我是新手。所以我猜我的控制器方法有问题?
标签: ajax asp.net-core asp.net-ajax