In this article I will explain with an example, how to Post
JSON to Controller without
AJAX in
ASP.Net Core (.Net Core 8)
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 a
PersonModel object.
Finally, user is redirect to the Index method.
public class HomeController : Controller
{
// GET: Home
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string json)
{
PersonModel personModel = JsonConvert.DeserializeObject<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
Inside the
Save JavaScript function, a
JSON object is created and
Name and
Age values are assigned.
Then the
JSON object 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>
<form method="post" asp-controller="Home" asp-action="Index">
<input type="hidden" name="json" value="" />
<input type="button" value="Save" onclick="Save()" />
</form>
<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 person = {};
person.Name = "Mudassar Khan";
person.Age = 40;
$("[name=json]").val(JSON.stringify(person));
document.forms[0].submit();
}
</script>
</body>
</html>
Screenshot
Downloads