In this article I will explain with an example, how to set value in Hidden Field created using Html.Hidden and Html.HiddenFor using JavaScript in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
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 JavaScript.
Each HTML INPUT Button is assigned with JavaScript onclick event handler.
Button for setting values
When Set button is clicked, the Set JavaScript function is called and the values of Name and Country are set in their respective Hidden Fields using JavaScript.
Button for getting values
When Get button is clicked, the Get JavaScript function is called and the values from the Hidden Fields are fetched using JavaScript and displayed using JavaScript Alert Message Box.
@model HiddenField_JavaScript_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" onclick="Set();" />
    <input type="button" id="btnGet" value="Get" onclick="Get();" />
 
    <script type="text/javascript">
        function Set() {
            document.getElementById("hfName").value = "Mudassar Khan";
            document.getElementById("hfCountry").value = "India";
        }
 
        function Get() {
            var name = document.getElementById("hfName").value;
            var country = document.getElementById("hfCountry").value;
            alert("Name: " + name + "\nCountry: " + country);
        }
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Set value in Hidden Field using JavaScript
 
 
Downloads