Home > database >  jsonserializer.serialize library failed
jsonserializer.serialize library failed

Time:12-06

public class Product
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
    }
public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product{Id = 1, ProductName= "Kulaklik", Quantity = 4},
                new Product{Id = 2, ProductName= "Şarj Kablosu", Quantity = 6},
                new Product{Id = 3, ProductName= "Akilli Saat", Quantity = 5}
            };
            

            string data = JsonSerializer.Serialize(products);

            // return View();


            TempData["x"] = 5;
            ViewBag.x = 5;
            ViewData["x"] = 5;

            return RedirectToAction("Index2");
            
        }
public IActionResult Index2()
        {

            var data = TempData["products"].ToString();
            List<Product> products = JsonSerializer.Deserialize<List<Product>>(data);


            return View();
        }

I have an Asp.Net Core Mvc project. I want to send data to another Action with JsonSerializer class. But among the overloads of the Serializer method there is no method that expects only a single value. I wonder what package I need to add for Visual Studio? serialize has a red line under it

CodePudding user response:

You probably have installed both - Newtonsoft.Json and System.Text.Json serializers. Newtonsoft.Json.JsonSerializer.Serialize doesnt have an overload with one argument and it causes an error. So you have to use a namespace to use anther serializer

string data = System.Text.Json.JsonSerializer.Serialize(products);

CodePudding user response:

Here is the solution

public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product{Id = 1, ProductName= "Kulaklik", Quantity = 4},
                new Product{Id = 2, ProductName= "Şarj Kablosu", Quantity = 6},
                new Product{Id = 3, ProductName= "Akilli Saat", Quantity = 5}
            };
            

            string data = JsonSerializer.Serialize(products);

            // return View();


            TempData["x"] = 5;
            ViewBag.x = 5;
            ViewData["x"] = 5;
           TempData["products"] = data; //you just need to add data into tempdata
            return RedirectToAction("Index2");
            
        }
  • Related