In this article I will explain with an example, how to set value in Hidden Field created using Html.Hidden and Html.HiddenFor using jQuery in ASP.Net MVC.
Model
The Model class consists of following property.
public class PersonModel
{
public string Name { get; set; }
}
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simple the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of two Hidden Fields and two HTML INPUT Buttons.
The Hidden Field for the Name value is created using Html.HiddenFor helper function, while the Hidden Field for the Country value is created using Html.Hidden helper function.
The Hidden Fields are assigned ID attribute using the HtmlAttributes parameter in their respective Helper functions so that the Hidden Fields can be accessed using jQuery.
Inside the View, the following jQuery script is inherited:
1. jquery.min.js
Each HTML INPUT Button is assigned with jQuery click event handler.
Button for setting values
When Set button is clicked, the values of Name and Country are set in their respective Hidden Fields using jQuery.
Button for getting values
When Get button is clicked, the values from the Hidden Field are fetched using jQuery and displayed using JavaScript Alert Message Box.
@model HiddenField_jQuery_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Html.HiddenFor(m => m.Name, new { @id = "hfName" })
@Html.Hidden("Country", "", new { @id = "hfCountry" })
<input type="button" id="btnSet" value="Set" />
<input type="button" id="btnGet" value="Get" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$("[id*=btnSet]").on("click", function () {
$("[id*=hfName]").val("Mudassar Khan");
$("[id*=hfCountry]").val("India");
});
$("[id*=btnGet]").on("click", function () {
var name = $("[id*=hfName]").val();
var country = $("[id*=hfCountry]").val();
alert("Name: " + name + "\nCountry: " + country);
});
</script>
</body>
</html>
Screenshot
Downloads