How to use javascript in a view using _layout.cshtml
I have a mvc 5 project. The general cshtml layout file uses normal javascript links for jquery and bootstrap.
I have a separate view where I added this code:
<div class="test">
@Html.CheckBoxFor(m => m.MyBool, new { @checked = "checked", onClick="toggleVisibility(this)" })
@Html.LabelFor(m => m.MyBool)
</div>
<div id="content">
my content
@Html.TextBoxFor(m => m.MyText, new { id = "TextBoxA", style = "width:20px;" })
<br />
<p>
Lorum ipsum
</p>
<p>
Lorem Ispum
</p>
</div>
When the checkbox is checked, I want to show or hide some things on the page. Javascript for this code:
function toggleVisibility(cb) {
var x = document.getElementById("content");
if (cb.checked == true)
//x.style.visibility = "visible"; // or x.style.display = "none";
$("#content").show("fast");
else
// x.style.visibility = "hidden"; //or x.style.display = "block";
$("#content").hide("fast");
}
The problem I am facing is that if I put this javascript in a shared file in the script tags I cannot use the function in my view, but if I use it in the view itself I have to manually add the script reference to the package jquery. Like this:
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript" language="javascript">
function toggleVisibility(cb) {
var x = document.getElementById("content");
if (cb.checked == true)
//x.style.visibility = "visible"; // or x.style.display = "none";
$("#content").show("fast");
else
// x.style.visibility = "hidden"; //or x.style.display = "block";
$("#content").hide("fast");
}
</script>
I am wondering if this is ok and if not, if there is a solution.
source to share
You can use section here
1. Create a section in sight.
@section scripts{
<script type="text/javascript" language="javascript">
function toggleVisibility(cb) {
var x = document.getElementById("content");
if (cb.checked == true)
//x.style.visibility = "visible"; // or x.style.display = "none";
$("#content").show("fast");
else
// x.style.visibility = "hidden"; //or x.style.display = "block";
$("#content").hide("fast");
}
</script>
}
-
Edit the section in _layout.cshtml after calling the package.
@RenderSection("scripts")
source to share