Hi Mousa,
Check this example. Now please take its reference and correct your code.
Model
public class BookModel
{
public List<Book> books { get; set; }
public double? averagePrice { get; set; }
}
public class Book
{
public int id { get; set; }
public string title { get; set; }
public int cost { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
BookModel bookModel = new BookModel
{
books = GetAllBooks(),
averagePrice = GetAverageBookPrice()
};
ViewBag.Json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(bookModel);
return View();
}
public List<Book> GetAllBooks()
{
List<Book> books = new List<Book>();
books.Add(new Book { id = 1, title = "Title 1", cost = 15 });
books.Add(new Book { id = 2, title = "Title 2", cost = 16 });
books.Add(new Book { id = 3, title = "Title 3", cost = 11 });
return books;
}
public double? GetAverageBookPrice()
{
return GetAllBooks().Select(x => x.cost).Average();
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@if (ViewBag.Json != null)
{
@ViewBag.Json
}
</body>
</html>
Screenshot