In this article I will explain with an example, how to use Html.Hidden and Html.HiddenFor Helper functions for creating Hidden Field in ASP.Net MVC.
Model
The Model class consists of following property.
public class PersonModel
{
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, an object of PersonModel class is created and the Name property is set which will be set in the Hidden Field created using Html.HiddenFor Helper function.
The value of the
Country is set in a
ViewBag object which will be later set in the Hidden Field created using
Html.Hidden helper function.
Finally, the PersonModel class object is returned to the View.
Action method for handling POST operation
Inside this Action method, the value of the Hidden Field created using the Html.HiddenFor Helper function is fetched using the Name property of PersonModel class object.
And the value of the Hidden Field created using the Html.Hidden Helper function is fetched using the Request.Form collection.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
PersonModel person = new PersonModel
{
Name = "Mudassar Khan"
};
ViewBag.Country = "India";
return View(person);
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
string name = person.Name;
string country = Request.Form["Country"];
return View();
}
}
View
HTML Markup
Inside the View, in the very first line the PersonModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the View, two Hidden Fields are created. The Hidden Field for the
Name value is created using
Html.HiddenFor function while the Hidden Field for the
Country value is created using
Html.Hidden Helper function and it is assigned with the value of the
ViewBag object.
The View also consists of a Submit Button which when clicked, the Form is submitted.
@model HiddenField_MVC.Models.PersonModel
@{
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))
{
@Html.HiddenFor(m => m.Name)
@Html.Hidden("Country", (object)ViewBag.Country)
<input type="submit" value="Submit" />
}
</body>
</html>
Screenshot
Downloads