I’m trying to create an HTML helper extension that generates some javascript in addition to an HTML tag:
<select id="foo" name="foo"></select>
<script type="text/javascript">
// script to populate select with data via $.getJSON
</script>
In the default MVC 4 template, they bundle the jquery scripts and put them at the end of the HTML document and have a scripts section:
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
Is there any way in an HTML helper extension to tell the script to get added to the end of the document, or do I just need to modify the Layout so that jQuery is at the top of the document?
Assuming you’re using a ViewModel for your view, one way to achieve what you’re after would be to separate the two things.
So in your View, you’d have something like this:
The block
@section scripts {}will render stuff where ever you placed the section in your layout (by default it’s after the jquery bundle).Create a folder called “App_Code” and inside that, create a razor file called “Helpers“. Paste the following inside:
This will create a dropdownlist that you need, and create a script block at the end and pass Model.Foo into it. I hope this was what you were after.