In this article I will explain with an example, how to Post
JSON Array to Controller without
AJAX in
ASP.Net MVC.
Installing Newtonsoft package using Nuget
Model
The Model class consists of following properties.
public class PersonModel
{
/// <summary>
/// Gets or sets Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets Age.
/// </summary>
public int Age { get; set; }
}
Namespaces
You will need to import the following namespaces.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the received
JSON string is deserialized into Generic List of
PersonModel objects.
Finally, user is redirect to the Index method.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string json)
{
List<PersonModel> persons = JsonConvert.DeserializeObject<List<PersonModel>>(json);
return RedirectToAction("Index");
}
}
View
HTML Markup
The View consists of a Form with an
HiddenField and a
Button.
Inside the View, following
jQuery file is inherited.
1. jquery.min.js
JavaScript Implementation
Then, some
JSON object are created and
Name and
Age values are assigned to them and then they are pushed into the
JavaScript Array.
The
JavaScript Array now consists of
JSON objects and it is converted into string using
JSON.stringify function and stored into the
Hidden Field.
Finally, the
Form is submitted which sends the
JSON string to the Controller.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input type="hidden" name="json" value="" />
<input type="button" value="Save" onclick="Save()" />
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
function Save() {
var persons = [];
var person = {};
person.Name = "John Hammond";
person.Age = 78;
persons.push(person);
person = {};
person.Name = "Mudassar Khan";
person.Age = 40;
persons.push(person);
person = {};
person.Name = "Suzanne Mathews";
person.Age = 33;
persons.push(person);
person = {};
person.Name = "Robert Schidner";
person.Age = 53;
persons.push(person);
$("[name=json]").val(JSON.stringify(persons));
document.forms[0].submit();
}
</script>
</body>
</html>
Screenshot
Downloads