How can I insert javascript in asp MVC application(view)?
I am doing following things in my javascript:
1) Read values from DOM elements.
2) Send data to Controler action method from Jquery Ajax.
3) Validating my input.
4) Read/Write cookies
How can I insert javascript in View.
Should it be something like this?
<script src="../Scripts/Jquery-2.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script>
$(document).ready(function ()
{
$.cookie("pc", "Navada, US");
}
);
</script>
@{
ViewBag.Title = "ViewPage1";
}
<h2>ViewPage1</h2>
Thanks for your answer
How can I insert javascript in asp MVC application(view)?
I am doing following things in my javascript:
1) Read values from DOM elements.
2) Send data to Controler action method from Jquery Ajax.
3) Validating my input.
4) Read/Write cookies
How can I insert javascript in View.
Should it be something like this?
<script src="../Scripts/Jquery-2.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script>
$(document).ready(function ()
{
$.cookie("pc", "Navada, US");
}
);
</script>
@{
ViewBag.Title = "ViewPage1";
}
<h2>ViewPage1</h2>
Thanks for your answer
Share Improve this question asked May 22, 2015 at 8:08 user786user786 4,3925 gold badges49 silver badges110 bronze badges 8-
1
Use the
<text>
. – Andrei V Commented May 22, 2015 at 8:10 - 1 I don't understand this question. Can you somehow elaborate? – Liam Commented May 22, 2015 at 8:11
- @AndreiV can you please elaborate what do you mean by <text.> – user786 Commented May 22, 2015 at 8:20
-
You can dynamically add text (e.g. JavaScript) to your view trough Razor, using the
<text>
tag. The are a lot of examples out there. Start with the link in my first ment. – Andrei V Commented May 22, 2015 at 8:22 - 1 @Liam In webforms we use <script> tag in header. In mvc view template there is no header template. But if there is, then correct me please. So my question is: the code in question is correct? I am using <script> tag at the top of view – user786 Commented May 22, 2015 at 8:22
1 Answer
Reset to default 4Not sure if i understand your question right, but if so you may need to put your script tags into the head tag.
To be able to put your custom js things into head you could try looking at this example:
In your _Layout page add this between <head></head>:
@RenderSection("CustomScripts", required: false);
And on your page:
@section CustomScripts
{
<script src="@Url.Content("~/Scripts/foo.js")" type="text/javascript"></script>
}
EDIT: as @Liam correctly pointed out that the _Layout file could be in any other path, @StephenMuecke's clarification applied.