In this article I will explain with an example, how to display (copy) TextBox value to Label using
jQuery in ASP.Net Core (.Net Core) 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
{
public IActionResult 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 an HTML INPUT TextBox, a Label and an HTML INPUT Button.
The TextBox has been assigned with a TagHelpers attribute asp-for which is set with the Name property of Model.
Inside the HTML Markup, the following script file is inherited:
1. jquery.min.js
Inside the
jQuery document ready event handler, the
Copy To Label Button has been assigned with a
jQuery click event handler.
When the Button is clicked, first the TextBox and Label controls are referenced and the TextBox value is set to the Label control.
@model Copy_TextBox_Label_jQuery_Core.Models.PersonModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input id="txtName" type="text" asp-for="Name" />
<input id=" btnCopyToLabel" type="button" value="CopyTo Label" />
<hr />
<label id="lblName"></label>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCopyToLabel").click(function () {
//Reference the TextBox.
var txtName = $("#txtName");
//Reference the Label.
var lblName = $("#lblName");
//Copy the TextBox value to Label.
lblName.html(txtName.val());
});
});
</script>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads