In this article I will explain with an example, how to display (show) TextBox value in Label using
JavaScript in ASP.Net MVC.
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, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
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 a TextBox and Label created using HTML.TextBoxFor and HTML.LabelFor Helper methods respectively and an HTML INPUT Button.
The Button has been assigned with an onclick event handler.
When the
Button is clicked, the
ShowName JavaScript function is called.
Inside this function, first the TextBox and Label elements are referenced and the TextBox value is set to the Label element.
@model Show_TextBox_Label_JavaScript_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Name:@Html.TextBoxFor(m => m.Name, new { id = "txtName" })
<input id="btnShowName" type="button" value="Show Name" onclick="ShowName()" />
<hr />
@Html.LabelFor(m => m.Name, " ", new { id = "lblName" })
<script type="text/javascript">
function ShowName() {
//Reference the TextBox.
var txtName = document.getElementById("txtName");
//Reference the Label.
var lblName = document.getElementById("lblName");
//Copy the TextBox value to Label.
lblName.innerHTML = txtName.value;
}
</script>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads