In this article I will explain with an example, how to disable or prevent CUT, COPY, PASTE and DROP options in TextBox and Multiline TextBox (TextArea) using jQuery in ASP.Net MVC.
Controller
The Controller consists of following two Action methods.
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
The View consists of a TextBox and a Multiline TextBox (TextArea) which has been created using the following HTML Helper functions:-
1. Html.TextBox – Creating a TextBox.
2. Html.TextArea – Creating a Multiline TextBox (TextArea).
The TextBox and Multiline TextBox (TextArea) have been set with disable CSS Class using class property.
Inside the jQuery document ready event handler, all the elements having the CSS Class disabled are referenced and for each element, Cut, Copy, Paste and Drop event handlers have been assigned.
Inside the Cut, Copy, Paste and Drop event handlers, the event has been cancelled by calling the return false statement.
So, when user tries to perform Cut, Copy, Paste and Drop operations, the operation will not be performed.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
</style>
</head>
<body>
@Html.TextBox("TextBox1", "", new { @class = "disable" })
<br/><br/>
@Html.TextArea("TextArea1", new { @class = "disable" })
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var controls = $(".disable");
controls.bind("paste", function () {
return false;
});
controls.bind("drop", function () {
return false;
});
controls.bind("cut", function () {
returnfalse;
});
controls.bind("copy", function () {
return false;
});
});
</script>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads