javascriptc#asp.net-mvcasp.net-coremodel-view-controller

Unable to send the List of model data to a view using asp.net mvc


I have a List<string> stored in local storage and I'm getting those values using javascript and sending it to a POST method of my controller using an AJAX call.

In the controller of the POST method an API is called in a for loop to fetch details in JSON format. After deserializing, it is getting stored in a List of model and this model needs to be sent to the view to display the list of data.

The model data needs to be passed to the view, but it is not happening and I am not sure where I am going wrong.

Model:

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;
  }
}

controller:

[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 to send the local storage values to the post controller method:

// 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);
  }
});

Solution

  • You are expecting a JSON result, but what you returned is return View("~/Views/FruitList", model);, This is the issue...

    You should return model instead. Try codes below:

    [Route("FruitController/FruitList")][HttpPost]
    public async Task <List<Fruit>> 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 model; // where the model has the data inside it.
    }