'While converting ViewBag.JsonData from View in JavaScript, getting The length of the string exceeds the value set on the maxJsonLength property
I'm working on a project where I've to pass a huge list of data (500 000 records or more) through ViewBag. From my controller, I'm sending data shown as below.
public ActionResult Index()
{
var list = new List<DropdownList>();
for (int i = 0; i < 500000; i++)
{
list.Add(new DropdownList() { id = i, text = "Test Data-" + i });
}
ViewBag.JsonData = JsonConvert.SerializeObject(list);
return View();
}
And from my view, I'm using the following code to parse that data in JavaScript. While trying this code getting the maxJsonLength exceeds the error.
<script>
$(document).ready(function(){
@Html.Raw(Json.Encode(@ViewBag.JsonData));
});
</script>
I also tried this & It's working with 500k records while data does not contain special characters. If data contain some special character then it's not working.
<script>
$(document).ready(function(){
JSON.parse('@ViewBag.JsonData');
});
</script>
Note: I'm not getting error in .cs (c# code) file cause this solution already implemented in my project.
Solution 1:[1]
You are getting the error in "C# code". This is not a JavaScript issue.
If editing web.config doesn't help, you can try using an instance of a JavascriptSerializer and setting the MaxJsonLength property manually:
@{
var serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };
var jsonData = serializer.Serialize(@ViewBag.JsonData);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oleg Naumov |
