Reputation: 2723
I have an mvc 5 project. In the shared layout cshtml file the usual javascript links to jquery and bootstrap.
I have a separate view where I have this code added into:
<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 check box is clicked I want to show or hide some stuff on the page. The javascript for that is 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 that I am having is that if I put this javascript in the shared file in script tags, I can not use the function in my view, but if I use it in the view itself I need to manually add the script link to the jquery bundle there as well. 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 normal and if not, if there is a solution to this.
Upvotes: 3
Views: 6442
Reputation: 949
You can use section here
1.Create a section in view.
@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>
}
Render section in your _layout.cshtml after the bundle call.
@RenderSection("scripts")
Upvotes: 4