In this article I will explain with an example, how to set Hidden Field value inside Controller in ASP.Net MVC Razor.
This article will illustrate how to set value of Hidden Field created using Html.Hidden helper function using ViewBag object in ASP.Net MVC Razor.
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the value of the Name is set in a ViewBag object which will be later set in the Hidden Field created using Html.Hidden helper function.
Action method for handling POST operation
Inside this Action method, 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()
{
ViewBag.Name = "Mudassar Khan";
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
string name = form["Name"];
return View();
}
}
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.
The Hidden Field for the Name value is created using Html.Hidden helper function and it is assigned value using ViewBag object.
There’s also a Submit Button at the end of the Form and when the Button is clicked, the Form is submitted.
@{
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.Hidden("Name", (object)ViewBag.Name)
<input type="submit" value="Submit"/>
}
</body>
</html>
Screenshot
Downloads