我有一个
List<string>
存储在本地存储中,我使用 javascript 获取这些值,并使用 AJAX 调用将其发送到我的控制器的 POST 方法。
在 POST 方法的控制器中,在
for
循环中调用 API 以获取 JSON 格式的详细信息。反序列化后,它被存储在模型的List
中,并且需要将该模型发送到视图以显示数据列表。
模型数据需要传递到视图,但它没有发生,我不确定哪里出错了。
型号:
public class Fruit
{
[JsonProperty("name")]
public string FruitName
{
get;
set;
}
[JsonProperty("image")]
public string ImageUrl
{
get;
set;
}
}
public class FruitDataModel
{
public List<Fruit> FruitData
{
get;
set;
}
}
控制器:
[HttpGet]
public ActionResult FruitList()
{
return View();
}
[Route("FruitController/FruitList")][HttpPost]
public async Task < ActionResult > FruitList(List<string> fruitItems)
{
var items = fruitItems;
List<Fruit> results = new List <Fruit>();
foreach(var item in items) {
var result = await CallApiAsync(item); //method returns the List of Fruit data
results.Add(result);
}
var model = new FruitDataModel {
FruitData = results
};
return View("~/Views/FruitList", model); // where the model has the data inside it.
}
View: @model Fruit.Models.FruitDataModel@ {
ViewBag.Title = "FruitList";
var index = 0;
}
@if (Model != null) {
foreach(var item in FruitData)
{
<li>@item.FruitName</li>
}
}
JS 将本地存储值发送到 post 控制器方法:
// I am using jQuery 3.3.1
const value = JSON.parse(localStorage.getItem('fruitItems')) || [];
console.log(value);
$.ajax({
url: '@Url.Action("FruitList", "Fruit")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(value), // Send localStorage value
dataType: 'json',
success: function (response) {
console.log('Data sent successfully');
},
error: function (xhr, status, error) {
console.error('Error sending data: ', error);
}
});
您期待的是 JSON 结果,但返回的是
return View("~/Views/FruitList", model);
,这就是问题...
你应该
return model
。并将 public async Task < ActionResult > FruitList 更改为 public async Task < List > FruitList