In this article I will explain with an example, how to use Html.TextAreaFor Helper method in ASP.Net MVC.
Model
The Model class consists of following property.
public class PersonModel
{
public string Message { get; set; }
}
Controller
The Controller consists of the following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned
Action method for handling POST operation
This Action method gets called, when Submit button is clicked.
This method accepts PersonModel class as parameter.
Inside this Action method, the value entered in the TextArea is fetched using
PersonModel class object and set into a
ViewBag object
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
ViewBag.Message = person.Message;
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.
The View also consists of a TextArea field created using Html.TextAreaFor Helper method and a Submit button.
Inside the Html.TextAreaFor Helper method, the lambda expression is used to specify the property of PersonModel class which is bound to it
Submitting the Form
When the
Submit Button is clicked, the
ViewBag object is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert Message Box.
@model TextAreaFor_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.TextAreaFor(m => m.Message)
<br />
<input id="btnSubmit" type="submit" value="Submit" />
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads