In this article I will explain with an example, how to pass (send) Label value from View to Controller in ASP.Net MVC Razor.
Label value cannot be sent to Controller directly and hence when the Submit Button is clicked and the Form is submitted, the Label value needs to be copied to a Hidden Field and then the value of the Label is extracted from the Hidden Field inside the Controller using Form Collection in ASP.Net MVC Razor.
Controller
The Controller consists of two 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 values of the Label is fetched using the Form Collection i.e. Request.Form collection using their Name attribute value of the Hidden Field.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
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 Form consists of a Label, a Hidden Field and a Submit Button.
The Submit Button has been assigned a JavaScript OnClick event handler and when it is clicked, the value of the Label is copied to the Hidden Field.
@{
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))
{
<label id="lblName">Mudassar Khan</label>
<hr/>
<input type="hidden" id="hfName" name="Name"/>
<input type="submit" value="Submit" onclick="OnSubmit()"/>
<script type="text/javascript">
function OnSubmit() {
document.getElementById("hfName").value = document.getElementById("lblName").innerHTML;
}
</script>
}
</body>
</html>
Screenshots
Form with Label
Label Value read from Form Collection
Downloads